3

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.

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
Peter Boomsma
  • 8,851
  • 16
  • 93
  • 185
  • 1
    You should be importing `styled` from `@mui/material/styles` instead of `@mui/system` in order to have access to the default theme. See:https://mui.com/system/styled/#import-path – Ryan Cogswell Oct 01 '21 at 00:41

1 Answers1

1

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";
NearHuscarl
  • 66,950
  • 18
  • 261
  • 230