TypeError: theme.spacing is not a function

Viewed 1880

I'm working on react app and using material-ui v5 and I'm stuck on this error theme.spacing is not working.

import { makeStyles } from "@material-ui/styles";
import React from "react";
import Drawer from "@mui/material/Drawer";
import Typography from "@mui/material/Typography";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import { AddCircleOutlineOutlined, SubjectOutlined } from "@mui/icons-material";
import { useHistory, useLocation } from "react-router";

const drawerWidth = 240;

const useStyles = makeStyles((theme) => {
  return {
    page: {
      background: "#f9f9f9",
      width: "100%",
      padding: theme.spacing(3),
    },
    drawer: {
      width: drawerWidth,
    },
    drawerPaper: {
      width: drawerWidth,
    },
    root: {
      display: "flex",
    },
    active: {
      background: "#f4f4f4 !important",
    },
  };
});

const Layout = ({ children }) => {
  const classes = useStyles();
  const history = useHistory();
  const location = useLocation();

  const menuItems = [
    {
      text: "My Notes",
      icon: <SubjectOutlined color="secondary" />,
      path: "/",
    },
    {
      text: "Create Note",
      icon: <AddCircleOutlineOutlined color="secondary" />,
      path: "/create",
    },
  ];

  return (
    <div className={classes.root}>
      
      <div className={classes.page}>{children}</div>
    </div>
  );
};

export default Layout;

on line no. 19 that is "padding: theme.spacing(3)" it is showing error on my browser

TypeError: theme.spacing is not a function

3 Answers

This is not working because you have to type your Theme

  1. import the Theme

    import { Theme } from '@mui/material'
    
  2. Now type it:

    const useStyles=makeStyles((theme:Theme)=>({
    
        root:{
            background: 'black',
            padding:theme.spacing(3),
        }
    
    }))
    

I was facing the exact same problem and this worked for me.

How do you create the theme, did you made with createTheme? You need to pass the provider in the root of your application. Try import like this.

import { createTheme } from '@mui/material/styles

Then define all your global styles for your application and then make, for example, this.

import { ThemeProvider } from "@mui/material/styles";
<ThemeProvider theme={yourtheme}><App/></ThemeProvider>

Maybe your import is wrong ? Try this

import {makeStyles} from "@material-ui/core/styles";
Related