Search code examples
cssreactjsstyled-components

How implement css mixes in styled-components?


I used in my projects some base classes like text-lg, text-md..., .container, etc. And usually I wrote classes in this way :

<div class="article text-lg container">some content</div>

How can I do something like this using styled-components? Create mixins for these classes, or just mix the use of of styled-components and css classes?


Solution

  • You can use the css helper to create your base classes and combine them.

    const container = css`
      padding: 20px;
    `;
    const article = css`
      max-width: 1920px;
    `;
    const textLg = css`
      font-size: 3rem;
    `;
    
    const CustomDiv = styled.div`
      ${container + article + textLg}
    
      /* other styles here */
      background: black; 
      color: white;
    `;
    

    Or if you already have an existing stylesheet (for example a CSS library such as Bootstrap), you can just combine them using attrs. This saves you the time of having to rewrite your CSS in JS. Read here for official docs: https://styled-components.com/docs/faqs#can-i-use-css-frameworks

    const CustomDiv = styled.div.attrs(props => ({
      className: "article text-lg container",
    }))`
      /* other styles here */
      background: black; 
      color: white;
    `;
    

    Basically, the output will be your custom generated class with background & color CSS properties in augmentation of article, text-lg, and container classes which is defined in your stylesheet

    HTML codes

    CSS codes