Styled Components

Learn how styled components work.

Getting started with styled-components

As apps grow, they can contain thousands of style rules, too many for a single person to keep track of. This leads to unintended conflicts. For example, which of the styles below will apply to a disabled button with the white class?

// StylesheetA.css
button.white {
  background-color: white;
  color: black;
}

// StylesheetB.css
button:disabled {
  background-color: grey;
  color: darkgrey;
}

The answer is that it depends on the order the stylesheets are loaded in, as both selectors have the same level of specificity. This is a very fragile state of affairs for a complex app. Worse, removing style rules becomes a risky endeavor. Let’s say that your app has this style rule:

p.alert-message {
  color: red;
}

You search your codebase for alert-message, find no results, and so you remove the style. But your search didn’t match this React code:

<p className={`${urgency}-message`}>This is an alert!</p>

Advantages of styled-components

The CSS-in-JS paradigm, exemplified by styled-components, greatly alleviates these problems by allowing a component’s style rules to be written as a function of its props. This offers a number of advantages:

  • There’s no need to search your codebase to find out which styles are associated with a component. Its styles are either in the same module or imported like any other dependency.

  • Styles are generated as a function of their component’s props and state, just like markup.

  • Styles can be subjected to unit tests.

  • Unlike the style prop, style rules generated by styled-components have the full range of functionality of ordinary CSS, including support for media queries, keyframe animations, and pseudo-classes.

Let’s start adding some style to test-driven-carousel. Install the styled-components package as a dependency:

$ npm install --save styled-components@4.1.1
+ styled-components@4.1.1

So far, this course’s methodology has been to present tests first, then the code to satisfy these tests. This is, after all, a course about TDD, and TDD is usually taken to mean “writing tests first.” But on a deeper level, TDD is about seeking useful feedback for your code as quickly as possible. Tests are just one possible source of feedback. And when it comes to styles, the most useful source of feedback is usually seeing those styles.

So set tests aside for now. All you’ll need for this section is a live dev server.

Get hands-on with 1200+ tech skills courses.