Search code examples
reactjsstyled-components

Conditional styled components effect all instances when nested


If i use a prop condition on the main component it will work per instance.

So for example if i have:

const Div = styled.div<Props>`
  ${(props) => {
    return css`
      ${props.test && "border: 5px solid red;"};


    `;
  }}
`;

only components which have the test prop will have this ugly border :)

But if i use this same condition on a nested css rule like that:

const Div = styled.div<Props>`
  ${(props) => {
    return css`
      .tabletScreen & {
        ${props.test && "border: 5px solid red;"};
      }
    `;
  }}
`;

All instances of this component will have this ugly border if one of the components has this test prop.

When inspect it i see that all instances of the component gets the same class generated, so the this:

.tabletScreen .sc-jcFjpl {
    border: 5px solid red;
}

Is implemented to all instances.

But on the first case (when the condition is not nested) the component with the test prop will get another class so it won't override the others.

How can i fix this?


Solution

  • Use && instead of & and it'll be scoped to that stylistic instance of the component. Single ampersand refers to the "static component class".

    More info here: https://styled-components.com/docs/basics#pseudoelements-pseudoselectors-and-nesting