[SOLVED] How to properly type the theme passed as prop to the styled() method on Material UI? (TypeScript)

Issue

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

Solution

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

Answered By – Asghwor

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *