Search code examples
reactjscssstyled-components

How to use joint selectors in styled-component


I have legacy CSS which looks like this:

.btn_1 {
    color: #fff;
    background: #004dda;
    display: inline-block;
}
.btn_1:hover {
  background-color: #FFC107;
  color: #222 !important;
}
.btn_1.full-width {
  display: block;
  width: 100%;
}

I want to migrate to using styled-components (CSS-in-JS style) in React.

This is my migration so far:

.btn_1 {
    color: #fff;
    background: #004dda;
    display: inline-block;
    :hover {
        background-color: #FFC107;
        color: #222 !important;
    }
}

but is there any solution in styled-components for selectors like .btn_1.full-width or I should just create another CSS block for that?


I think it would be cool to do something like this (or better):

.btn_1 {
    ${this}.full-width {
        display: block;
        width: 100%;
   }
}

but I can't seem to find the solution in the documents. Do you have any idea how this is possible or is this even a good idea?


Solution

  • from official styled components documentation

    For complex selector patterns, the ampersand (&) can be used to refer back to the main component. Here are some more examples of its potential usage:

    const Thing = styled.div.attrs({ tabIndex: 0 })`
      color: blue;
    
      &:hover {
        color: red; // <Thing> when hovered
      }
    
      & ~ & {
        background: tomato; // <Thing> as a sibling of <Thing>, but maybe not directly next to it
      }
    
      & + & {
        background: lime; // <Thing> next to <Thing>
      }
    
      &.something {
        background: orange; // <Thing> tagged with an additional CSS class ".something"
      }
    
      .something-else & {
        border: 1px solid; // <Thing> inside another element labeled ".something-else"
      }
    `