Search code examples
cssreactjsstyled-components

Style rules based on wrapping parent classes


I'm pulling some components from my react app into a component library, and updating them to be styled-components so I can use them in another project ssr. First step: get these components working in a library as styled-components for the current project

I have a component which currently has additional scss rules when it is used within certain parents. e.g.

.myElement {
  border: 1px solid red;
}
.specialCase {
  .myElement {
    border: 1px solid blue;
  }
}

How do I adapt this into a styled component? If I have my styled component like:

styled(MyElement)`
  border: 1px solid red;
`

Obviously I cant use the .specialCase parent selector in here.

I have a couple of restrictions - the component higher up that provides the .specialCase class is not a styled component, and is not in the component library. Also I do not want to have conditional rules in the component, as I want this style change to happen without a react rerender. i.e. when the class is added to it's parent, it shouldn't have to rerender myElement.

Can anyone help me with an approach that might solve this? I am new to styled-components


Solution

  • The parent component can still select .myElement, you just need to add a className="myElement" to the styled component.

    In the next example, Container can be any component (don't have to be styled):

    const Container = styled.div`
      .myElement {
        border: 2px solid blue;
      }
    `;
    
    const Child = styled.div`
      border: 1px solid red;
    `;
    
    const App = () => {
      return (
        <Container>
          <Child className="myElement">Hello</Child>
        </Container>
      );
    };
    

    Edit quiet-frost-do2hs