How to Reuse Common CSS in styled-components?

To adhere to the "Don't Repeat Yourself" (aka DRY) principle, you could do either of the following to reuse common bits of CSS in your styled-components:

For examples in this post, you can maybe consider the following basic "Shapes" component (where the "Square" and "Rectangle" styled-components are expected to have some common styling):

const Shapes = () => (
    <>
      <Square>Foo</Square>
      <Rectangle>Bar</Rectangle>
    </>
);

ReactDOM.render(<Shapes />, document.getElementById('root'));

Extract Common Styles Into a Separate Variable

If you have a part of CSS that is common between two or more components, then you could simply extract it into an individual JavaScript variable and make it reusable using the css helper function, for example, like so:

import styled, { css } from 'styled-components';

const CommonStyle = css`
    height: 50px;
    color: blue;
    text-align: center;
    background-color: aqua;
`;

You could then easily use that variable inside the "tagged templates" syntax of any styled-component. For example:

const Square = styled.div`
    width: 50px;
    ${CommonStyle}
`;

const Rectangle = styled.div`
    width: 100px;
    ${CommonStyle}
`;

Extend the Styles of an Existing Component

By extending an existing component, your new component can inherit its styling from the component it extends. To achieve that you can simply pass the styled-component you wish to extend (or inherit styles from) to the styled() constructor, for example, like so:

import styled from 'styled-components';

const Square = styled.div`
    width: 50px;
    height: 50px;
    color: blue;
    text-align: center;
    background-color: aqua;
`;

const Rectangle = styled(Square)`
    width: 100px;
`;

Please note that this would also inherit the HTML tag of the styled-component you extend from. In cases where you wish to use a different HTML element for each component, you could extract common styles into separate variable(s) instead.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.