Search code examples
reactjspseudo-elementstyled-componentspseudo-class

Nth-child of styled component not working


I created a ReactComponet called FilterOptions. Which i'm going to use like this:

<Filter>
   <FilterOptions> example1 </FilterOptions>
   <FilterOptions> example2 </FilterOptions>
   <FilterOptions> example3 </FilterOptions>
<Filter>

I just want that the first "FilterOptions" have a red background.

Inside the FilterOptions, the most outside Container has a &:nth-child(1) which I'm trying to use, but doesn't work for some reason? :

export const Container = styled.div
   background: ${({theme}) => theme.COLORS.HIGHLIGHT};
   padding: 8px 14px;
   margin-top: 15px;
   border-radius: 18px;
   display: flex;
   flex-flow: row nowrap;
   align-items: center;
   &:nth-child(1) {
      background: red;
      height: 200px;
      width: 300px;
      margin: 200px;
   };
;

I've already tried lots of combinations like &:nth-child(1), :nth-child(1), ::nth-child(1), &&:nth-child(1). Don't know what's wrong here.


Solution

  • Just a small change to what HermitCrab answered, for my styled-component to work it should be this:

    <Filter>
       <Container> example1 </FilterOptions>
       <Container> example2 </FilterOptions>
       <Container> example3 </FilterOptions>
    <Filter>
    

    because &:nth-child(1) checks if the Component itself is the first-child (Container in this case)