I want to use the default Material UI theme colors in a custom form element:
import * as React from 'react';
import { styled } from '@mui/system';
const MyComponent = styled('div')(({theme}) => ({
color: 'darkslategray',
padding: theme.spacing(8),
borderRadius: theme.shape.borderRadius,
backgroundColor: theme.palette.primary.main,
}));
export default function BasicUsage() {
return <MyComponent>Styled div</MyComponent>;
}
https://codesandbox.io/s/hwpzf?file=/demo.tsx
Returns error:
Cannot read properties of undefined (reading 'main')
I can use the default spacing values or borderRadius provided by theme, but not the palette.
It's because you import the styled function from @mui/system:
import { styled } from '@mui/system';
The styling API from '@mui/system' doesn't have a default theme, so you need to create a theme yourself and register in ThemeProvider. If you wish to use the material default theme without writing extra code, use '@mui/material/styles':
import { styled } from "@mui/material/styles";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With