Home > database >  How to properly type the theme passed as prop to the styled() method on Material UI? (TypeScript)
How to properly type the theme passed as prop to the styled() method on Material UI? (TypeScript)

Time:03-18

I'm using Material UI with its styled function to stylize components, such as:

const MyThemeComponent = styled("div")(({ theme }) => `
  color: ${theme.palette.primary.contrastText};
  background-color: ${theme.palette.primary.main};
  padding: ${theme.spacing(1)};
  borderRadius: ${theme.shape.borderRadius};
`);

It works, but the typing does not, showing the fields, after written, as of type any. So, we're left without autocomplete, suggestions or error checking.

How can I have the typing working properly within the styled() method?

demo

CodePudding user response:

does that work for you https://codesandbox.io/s/themeusage-material-demo-forked-pikixf. I can't really test it properly if the autocomplete is working in the codesandbox.

CodePudding user response:

Fixed it by using the Emotion / Styled-Components format instead of the MUI format shown in the documentation.

const MyThemeComponent = styled("div")`
  color: ${({ theme }) => theme.palette.primary.contrastText};
  background-color: ${({ theme }) => theme.palette.primary.main};
  padding: ${({ theme }) => theme.spacing(2)};
  border-radius: ${({ theme }) => theme.shape.borderRadius}px;
`;

fixed demo

  • Related