Home > other >  How to import CSSProperties from MUI v5?
How to import CSSProperties from MUI v5?

Time:03-29

I have a lot of components which bring in styles as props. Simple stuff like:

import { CSSProperties } from '@material-ui/styles/withStyles' // importing from mui v4 because I don't know how to do so from v5 paths
import { styled } from '@mui/material'

const StyledDiv = styled('div')(({ theme, customStyles }: StyledDivType) => ({
  color: theme.palette.text.primary,
  ...customStyles
}))

export const MyComponent = (customStyles: CSSProperties) => (
  <StyledDiv customStyles={customStyles}>My component</StyledDiv>
)

// Usage:
const App = () => (
  <MyComponent customStyles={{ padding: 10, backgroundColor: 'blue' }}/>
)

The thing is, for typing purposes, I cannot find the right place to import the CSSProperties type from MUI v5. Where would be the proper place to import that so I can remove all MUI v4 import paths?

Thanks!

CodePudding user response:

The equivalent import in v5 is:

import { CSSProperties } from '@mui/material/styles/createTypography';

Exported here: https://github.com/mui/material-ui/blob/v5.5.3/packages/mui-material/src/styles/createTypography.d.ts#L41

The downside of this approach is that this would be considered a third-level import which means the following portion of the documentation applies:

Be aware that we only support first and second-level imports. Anything deeper is considered private and can cause issues, such as module duplication in your bundle.

It would also work to use:

import { CSSProperties } from '@mui/styles/withStyles';

Exported here: https://github.com/mui/material-ui/blob/v5.5.3/packages/mui-styles/src/withStyles/withStyles.d.ts#L22

If you are not otherwise dependent on @mui/styles, it would seem unfortunate to pull it in purely for the sake of this import, but given the downsides of the other approach, I don't have a strong opinion on which approach you should take.

  • Related