Search code examples
reactjsmaterial-uiemotion

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

  • 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.