Home > Net >  MUI - How to use pseudo class in specific styled component
MUI - How to use pseudo class in specific styled component

Time:10-28

I'm new to whole react and MUI styled components. Right now I'm working on a grid and I would like to style all children of specific component. What I would like to do is a ${Item1}:nth-child(3n-1), ${Item2}:nth-child(3n-1), ${Item3}:nth-child(3n-1) but it does not work like this:

const Grid = styled('div')(({ theme }) => ({
    width: '100%',
    height: '100%',
    padding: 0,
    display: 'grid',
    gap: 0,
    gridTemplateColumns: 'repeat(3,minmax(0,1fr))',
    `${Item1}:nth-child(3n-1)`: {
        backgroundColor: 'lightYellow'
    },
    gridTemplateColumns: 'repeat(3,minmax(0,1fr))',
    `${Item2}:nth-child(3n-1)`: {
        backgroundColor: 'lightGreen'
    },
    gridTemplateColumns: 'repeat(3,minmax(0,1fr))',
    `${Item3}:nth-child(3n-1)`: {
        backgroundColor: 'lightBlue'
    }
}

const Item1 = styled('div')(({ theme }) => ({
    ...
}));

const Item2 = styled('div')(({ theme }) => ({
    ...    
}));

const Item3 = styled('div')(({ theme }) => ({
    ...
}));

<Grid>
    <Item1 />
    <Item2 />
    <Item3 />

    <Item1 />
    <Item2 />
    <Item3 />

    <Item1 />
    <Item2 />
    <Item3 />
<Grid>

CodePudding user response:

Item is the direct children of Grid so you can use div > div selector:

const Grid = styled('div')(({ theme }) => ({
  ...,
  '& > :nth-child(3n-2)': {
    backgroundColor: 'lightYellow',
  },
  '& > :nth-child(3n-1)': {
    backgroundColor: 'lightGreen',
  },
  '& > :nth-child(3n)': {
    backgroundColor: 'lightBlue',
  },
}));

If you want to target a specific child, you can add a class name to identify it:

const Grid = styled('div')(({ theme }) => ({
  ...,
  '& > .item1': {
    backgroundColor: 'lightYellow',
  },
  '& > .item2': {
    backgroundColor: 'lightGreen',
  },
  '& > .item3': {
    backgroundColor: 'lightBlue',
  },
}));
<Grid>
  <Item className="item1" />
  <Item className="item2" />
  <Item className="item3" />

  <Item className="item1" />
  <Item className="item2" />
  <Item className="item3" />

  <Item className="item1" />
  <Item className="item2" />
  <Item className="item3" />
</Grid>

Codesandbox Demo

  • Related