Skip to content
Advertisement

Prepend static parent class before Styled-Component classes

I am trying to figure out something with our Styled Component App. For the context, we create a app that will live inside a website that already has its own global style sheet. The problem is, when we plug in the application within the website, plenty of our generated style is overridden by the global stylesheet, which uses a parent class to wrap some elements.

Generated HTML

<div class="PARENT_CLASS">
  <div id="PARENT_ID">
    <div id="MY_APP">
      <div class="sc-gtsrHT ddDIoa test-wrapper">
        <a href="/">Click me</a>
      </div>
    </div>
  </div>  
</div>

Generated CSS

/* WEBSITE STYLE */
.PARENT_CLASS #PARENT_ID a {
  color: #0ae;
}

/* SC GENERATED */
.ddDIoa a {
  color: red;
}

React Javascript

const TestWrapper = styled.div`
  a {
    color: red;
  }
`;

const A = styled.a`
  color: red;
`;

const Content = () => (
  <TestWrapper className="test-wrapper">
    <A href="/">Click me</A>
  </TestWrapper>
);

Is there way to prepend the static classes (.PARENT_CLASS #PARENT_ID) to all generated classes by Styled Component without having to do on every single Component I create.

Thx

Advertisement

Answer

This problem is answered here in styled component documentation. Highlighted Documentation

This solution uses babel-plugin-styled-components-css-namespace to prepend classes/ids to all your styled component components.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement