'How to properly type the theme passed as prop to the styled() method on Material UI? (TypeScript)
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?
Solution 1:[1]
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;
`;
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Asghwor |
| Solution 2 | christiansany |
