Search code examples
reactjsstyled-components

styled-components: using `& + &` selector and adapt based on props


I have some components rendered with the same styled-component, and I want to make some margin-top between them

const Item = styled.div`
  color: ${props => props.active ? 'red' : '#333'};
  & + & {
    margin-top: 10px;
  }
`

<Item active={false}/>
<Item active={false}/>
<Item active={false}/>

so far so good,

but when one of them has a true active prop, the margin-top is missing, I found that is because <Item active={false}/> and <Item active={true} /> do not have the same class name.

Is there a way to fix this issue?

P.S.

I'm just get started with styled-components, and I'm also looking for best practice with it.


Solution

  • the components should have the same class name as they are using the same styled-components component.

    But regarding the & + &, if you want all of them, then just plain margin-top: 10px is enough, if you want to do on in between, you can just specify the first-child, last-child to be margin: 0.

    <React.Fragment>
      <Item active={false}>First</Item>
      <Item active={false}>Second</Item>
      <Item active={false}>Third</Item>
    </React.Fragment>
    

    A codesandbox for demo: https://codesandbox.io/s/62l02knn5r