In this tutorial, you will learn a new approach to styling ReactJS components, using styled-components.
styled-component will prevent name clashes. When the component is compiled a unique hash is generated, like so:
Let us compare how we write traditional CSS with CSS written using
As the name implies, when creating CSS using
styled-component you follow a component-based approach. Instead of attaching CSS via a
classNames we create our CSS within a ReactJS component:
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 need to use
className on your components. The result of this process is that the JSX is easier to reason about and has better semantic meaning. It is easier to understand what is going on when using components. In the first traditional example, you have to have an understanding of HTML and how the code works before you can understand what is going on. Using
styled-component a developer can ensure that the intention of the HTML is easily communicated to the reader.
Installing Styled Components
styled-componenta from NPM is done using this command:
Styling a component using
styled-components is done using ES2015 tagged template literals, otherwise known as the back-tick!
The component in this example will be called
button. If you wanted the containing tag to be a
<div>, you would do this:
To output the component tag as a link can be done like this:
You can write pretty much any CSS you want with the component, including pseudos and media queries. You will also likely want to test your component. Now the CSS is written in JS, you can even unit test it and create snapshot tests using Jest Styled Components. To install it you can use:
Here’s an example of a test written for a
This is not the only approach that you can use with
styled-components. Some teams like to work using multiple files, keeping the react component in one file and the styling in a separate file. For example, a file called
myComponent.ts would contain the component code and a file called
myComponent.styled.ts would contain any
styled-components. My preference is to have everything in a single place. If files get too big and cumbersome, this is a sign of bad component design. This warning sign is a good reminder to split things into smaller components.
As I am hoping you agree there are some good benefits from using this package and it is worth considering. Happy coding!