Search code examples
javascripthtmlcssreactjsstyled-components

Inherit CSS classes in styled-components definitions?


I want to style my app using styled-components where my components inherit styles from existing globally defined CSS. In the example below, how can I make Surface inherit the classes .raised and .bordered so that I don't have to repeat className="raised bordered" in each usage? I want something similar to Composition in Emotion.

https://codesandbox.io/s/optimistic-ramanujan-xs8rt

App.js

import "./styles.css";
import styled from "styled-components";

const App = () => (
  <div>
    <Surface className="raised bordered">Hello World 1</Surface>
    <Surface className="raised bordered">Hello World 2</Surface>
    <Surface className="raised bordered">Hello World 3</Surface>
  </div>
);

const Surface = styled.div`
  color: darkblue;
  margin: 20px;
`;

export default App;

styles.css

.raised {
  box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
}

.bordered {
  border: 1px solid black;
}

Solution

  • This is doable using attrs as shown below

    import "./styles.css";
    import styled from "styled-components";
    
    const App = () => (
      <>
        <Surface>Hello World 1</Surface>
        <Surface>Hello World 2</Surface>
        <Surface>Hello World 3</Surface>
      </>
    );
    
    const Surface = styled.div.attrs({
      className: "raised bordered"
    })`
      color: darkblue;
      margin: 20px;
    `;
    
    export default App;