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

Creating a button React component with dynamic styles using styled-components

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 using global theme for colors, spacing, fonts, etc. instead of hardcoding this values in the component.

We’ve a basic button component that works okay, and we can tweak styles to match the design perfectly, but it has a problem. If we keep adding components with hardcoded colors, spacing, and so on, and then decide to change some of them, we’d have to update all components that are using these values.

Another thing that might be useful is contextual styling. Imagine a footer with a subscription form, and this footer has dark background, so we need to invert colors of all components inside the footer.

A naïve approach would be to hardcode both themes inside each component, and add a prop to switch between them. But this is very hard to maintain: just for this button component we’d have to keep four variations — light primary, light secondary, dark primary, and dark secondary. Also we’d have to pass a props to each component when we want a dark variation. Much better solution would be to use React Context and theme provider from styled-components to do all the work for us. But to do so, we need to read colors, spacing and all other design tokens from styled-components theme.

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

Useful links and documentation:

egghead
egghead
~ 13 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