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

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.



Solution 1:[1]

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}>

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 st.huber
Solution 2 Crferreira