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

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 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: