In this tutorial, you will learn a new approach to styling React.js components, using styled-components. Styled component is a CSS-in-JS framework. CSS-in-JS is a similar concept to using JSX within React.js. Instead of writing CSS within a CSS or SASS file, you write your CSS within Javascript. When the CSS/JavaScript is parsed, CSS is generated which is attached directly on top of the DOM.

There are a number of benefits of using CSS-in-JS. First, the CSS has located the same file as the component. Second, using CSS-in-JS allows you to write more declarative code. To style a component you wrap it within a styled-component. For example, using traditional CSS you may write something like this:

With styled-components you focus on the component and its intention. Instead of attaching the CSS via classNames we create a styled-components instead:

When you compare the two approaches you can start to see styled-component allows you to concentrate on intention rather than syntax. Gone is the className. The end JSX is easier to reason about as it has semantic meaning about what the component meant to do. In the first example, you have to read the code to understand its a submit button. Using styled-components a developer can ensure that the intention of the component is easily communicated to anyone else reading the code by following a good naming convention.

A second benefit of using styled-component is that it prevent name clashes. When the component is compiled a unique hash is generated, like so:

With these hashes, there is no chance of different components CSS interfering with each other.

Installing Styled Components

You can install styled-components from NPM:

To style a component using styled-components we define the CSS in a separate componentStyled-components makes use of ES2015 tagged template literals which then accepts CSS, like so:

The end HTML will be a button. If you wanted to put a div, you would do this:

Or a link:

You can add any CSS with the styled-component, including pseudos and media queries. You will also likely want to test your components. Now the CSS is written in JS you can even unit test them, using Jest Styled Components. To install it you can use:

Here’s an example of a test:

There are a number of different approaches you can use with styled-components. Some teams like to keep all the styling in a separate file. myComponent.ts will contain the component and myComponent.styled.ts contains the CSS. My preference is to have everything in a single place, however, if the component starts to get too large then splitting it up in this manner can make the code cleaner and easier to understand.