Simplifying styled-components styles by using Styled System CSS and variants

Artem Sapegin
InstructorArtem Sapegin

Share this video with your friends

Send Tweet
Published a year ago
Updated 10 months ago

In this lesson we’ll improve a generic button primitive component by refactoring it with Styled System to simplify the implementation.

The naïve styled-component implementation has styles like this:

padding: ${props =>[3]} ${props =>[4]};
color: ${props =>
  props.variant === 'primary'
    ? props.theme.colors.background
    : props.theme.colors.primary
background-color: ${props =>
  props.variant === 'primary'
    ? props.theme.colors.primary
    : props.theme.colors.background};

This kind of code isn’t very readable and isn’t easy to change. We can improve it a bit by extracting styles of each variant into its own object but there’s a better solution: Styled System.

Styled System is a tool that allows us to create primitive components where we can control styles using component props, and all these props are constrained by our design system and responsive.

For this component we’ll use two features of Styled System: CSS and Variants:

  • CSS helps us define common styles for both, primary and secondary, variants.
  • Variants allows us to switch multiple style properties with a single component prop, exactly what we need to implement primary and secondary styles.

We’ll use following libraries:

You can either use this lesson’s Git repository or install them manually in your project:

npm install styled-components styled-system @styled-system/css

Useful links and documentation: