JasonGenX
JasonGenX

Reputation: 5434

React + Styled Components - separating and re-using css "bundles"

I have this code I'm applying to a rendered react component.

const AdBannerBaseStyle = `
   display: block;
   text-align: center;
   font-size: 2em;`;

 const AdBannerStyle = styled.div`
     ${ AdBannerBaseStyle }      
 `;

 const AdBannerStyleDev = styled.div`
   ${ AdBannerBaseStyle }
   background: yellow;
 `;

The code above works as intended, but WebStorm complains about the explicit background: yellow which makes me think there may be a more elegant way of achieving this.

Is there? I would appreciate knowing if there's a better way, pattern to get this done.

Upvotes: 1

Views: 90

Answers (1)

sgarcia.dev
sgarcia.dev

Reputation: 6170

If Webstorm is the one complaining, it might be because you are hardcoding a named color instead of using it's HEX or RGB color value. However, if your question is aligned more towards Is there a better way or pattern to reuse CSS using styled components?, then I would say yes. Have you looked into extending styles? Here TomatoButton is based on the styles from Button.

// The Button from the last section without the interpolations
const Button = styled.button`
  color: palevioletred;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;
// A new component based on Button, but with some override styles
const TomatoButton = styled(Button)`
  color: tomato;
  border-color: tomato;
`;
render(
  <div>
    <Button>Normal Button</Button>
    <TomatoButton>Tomato Button</TomatoButton>
  </div>
);

From the Styled Components Docs.

Upvotes: 1

Related Questions