Kay
Kay

Reputation: 19718

Material UI v5 - Property 'spacing' does not exist on type 'DefaultTheme' when using a custom theme

I am using material ui version 5, i have a custom theme which i have wrapped in all my components around.

In one of my components i am trying to give paper some padding based on my theme, however i get the following error.

Property 'spacing' does not exist on type 'DefaultTheme'

       <AppProvider>
            <Theme>
                <Layout>
                    <ProtectedRoute>
                        <Component {...pageProps} />
                    </ProtectedRoute>
                </Layout>
            </Theme>
        </AppProvider>

campaign.tsx

const useStyles = makeStyles((theme) => ({
    paper: {
        padding: theme.spacing(3),
    },
}));

export default function Campaign(props: ICampaginProps): ReactElement | null {
    const classes = useStyles();

theme.tsx

const DEFAULT_THEME = createTheme({
    typography: {
        fontSize: 12,
    },
    palette: {
        mode: "light",
        primary: {
            main: "#212121",
        },
        secondary: {
            main: "#fafafa",
        },
    },
});

Upvotes: 13

Views: 9190

Answers (2)

Other solution I found is to type theme and import styled from mui. I'm using an alias to styled in the case anyone uses emotion or styled components and wants to use that CSS.

    import { Theme, styled as styledMui } from '@mui/material/styles';
import { Paper } from '@mui/material'

    export const CustomPaper = styledMui(Paper)(({ theme }: { theme: Theme }) => `
  padding: ${theme.spacing(3)};
`);;

Or following the object alternative:

export const CustomPaper = styledMui(Paper)(({ theme }: { theme: Theme }) => ({
  padding: theme.spacing(3),
}));

Upvotes: 0

Steve G
Steve G

Reputation: 13462

Have you tried this suggestion from the MUI migration documentation:

[Types] Property "palette", "spacing" does not exist on type 'DefaultTheme'

Since makeStyles is now exported from @mui/styles package which does not know about Theme in the core package. To fix this, you need to augment the DefaultTheme (empty object) in @mui/styles with Theme from the core.

TypeScript Project

Put this snippet to your theme file:

// it could be your App.tsx file or theme file that is included in your tsconfig.json
import { Theme } from '@mui/material/styles';

declare module '@mui/styles/defaultTheme' {
  // eslint-disable-next-line @typescript-eslint/no-empty-interface (remove this line if you don't have the rule enabled)
  interface DefaultTheme extends Theme {}
}

Javascript Project

If your IDE (ex. VSCode) is able to infer types from d.ts file, create index.d.ts in your src folder with this snippet:

// index.d.ts
declare module "@mui/private-theming" {
  import type { Theme } from "@mui/material/styles";

  interface DefaultTheme extends Theme {}
}

Upvotes: 14

Related Questions