Search code examples
reactjsstyled-components

Override styled-components in React


I'm trying to find a way to override a styled component with styled-components like this:

Let's say I have a reusable component Wrapper:

class Wrapper extends Component {

  ...

  render() {
    const Wrap = styled.div`
      padding: 5px;
      background-color: green;
    `;
    return (
       <Wrap>
         {children}
       </Wrap>
    )
  }
}

export default Wrapper

And then I have Component B that imports Wrapper but should extend the styles like this: myNewWrap uses Wrapper

import Wrapper from './Wrapper'

class B extends Component {

  ...

  render() {
    const myNewWrap = styled(Wrapper)`
      background-color: red;
    `;
    return (
       <myNewWrap>
         Some awesome text
       </myNewWrap>
    )
  }
}

Result should be that Some awesome text has padding from Wrapper but background-color from own component. But what I get is only the styles from Wrapper.


Solution

  • Have you considered using extend from Styled-Components? Styled generates new component styles with a new class whereas extend is meant to use base styling from another Styled component, but then tweak or add additional styles.

    Additionally, their docs explain when you should you use styled() (see section "When should I use styled()?") when to use styled