Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use palette colors from MUI theme

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.

like image 224
Peter Boomsma Avatar asked Jan 22 '26 08:01

Peter Boomsma


1 Answers

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";
like image 189
NearHuscarl Avatar answered Jan 24 '26 21:01

NearHuscarl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!