Search code examples
cssreactjsmaterial-uitsx

Styling MUI components in React with CSS


I want to style all the <Chip> inside the <Grid> that has the class .table-header but they does not change ther style (i put a <p> that should be colored in red and it works). Why it works for the <p> and not for the <Chip>? I want to do this without putting the same class in each <Chip>.

I am using MUI v5.11.4

portion of tsx code:

<Grid className={classes['table-header']}>
  <Grid item xs={1} />
  <Grid item xs={2}>
    <Chip avatar={<Avatar>1</Avatar>} label="Element1" />
    <p>Red text</p>
  </Grid>
  <Grid item xs={4}>
    <Chip avatar={<Avatar>2</Avatar>} label="Element2" />
  </Grid>
  <Grid item xs={5} />
</Grid>

module.css code:

.table-header Chip {
  width: 100%;
}

.table-header p {
  color: red;
}

CODE SANDBOX


Solution

  • You need to set your selectors in the right way. Here how you can set the styled component for the Chip:

    // import styled components
    import { styled } from "@mui/system";
    
    // Create the styled component for the Chip
      const StyledChip = styled(Chip)({
        "& .MuiChip-label": {
          color: "red"
        }
      });
    
    // Use it like this example:
    <StyledChip avatar={<Avatar>1</Avatar>} label="Element1" />
    

    Here is a working codesandbox with your solution.

    UPDATE: Based on your comment that you don't want to use styled component, I was able to do it like this:

    .table-header :global .MuiChip-label {
      color: red;
    }
    

    You need to mark the .MuiChip-label class as :global

    Here is the codesandbox with the second solution