MUI v5 : How to pass css classes to components using className prop? Also I want to use theme in those classes?

Viewed 792

MUI v5 : How to pass css classes to components using className prop? Also I want to use theme in those classes? I was trying to do it using styled in MUIv5, but if am not wrong we can target certain classes using styled but cannot pass those classes to the component.

2 Answers

You need to first import that css file in that component.Then you can pass it like this

<div className={name of your class that you imported}>

One way for achieving this is to define the css class at a sx property of a parent component, like in the following example:

function Child({ message, className }) {
  return <Typography className={className}>{message}</Typography>;
}

function Parent() {
  return (
    <Box
      sx={{
        '.childClass': {
          color: 'primary.main'
        }
      }}
    >
      <Child message="Child with no css class defined" />

      <Child className="childClass" message="Child with css class defined" />
    </Box>
  );
}

In this example, 'primary.main' resolves to theme.pallete.primary.main, as mentioned here.

Related