⚠️ This lesson is retired and might contain outdated information.

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

Artem Sapegin
InstructorArtem Sapegin
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 2 years 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 => props.theme.space[3]} ${props => props.theme.space[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:

egghead
egghead
~ 46 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today