React components: add CSS with clean code

Read this post in Spanish here.

When it comes to designing applications with React, there are many ways to add style to components. The ones I knew so far were the following:

  1. Import a CSS file with the necessary classes and use the JSX property “className” to add them to the component.
  2. Use the “style” property to add inline style.

The disadvantage of the first option is that you have to create an additional file to create a component and it complicates the maintenance of the code a bit. Also, you have to manually avoid class name collision between components.

On the other hand, the main drawback of the second option is that you cannot copy CSS from the browser inspector and paste it into our code, or vice versa, because the “style” property of our component receives an object and the properties of the objects cannot have the “-” character in the name, so the properties must be rewritten. Also, the property value must be quoted to convert it to text. All of this slows down development because you have to retype what you test in the browser. For example, to add the following CSS snippet to a component:

element.style {
min-height: 626px;
border: 1px solid red;
background-color: white;
}

We would have to create the following object in our code:

const style = {
minHeight: '626px',
border: '1px solid red',
backgroundColor: 'white'
};

In this post I share a clean way to style components using “styled-components”.

Styled-components is a library that creates React components with embedded styles using template literals.

Some of the advantages of this library are the following:

  • Creates class names automatically to avoid collisions.
  • Templates use CSS syntax.
  • Allows conditional rendering based on properties.
  • Adds vendor prefixes automatically.

Example of use

To install the library, you have to execute the following command (the types can be omitted if TypeScript is not used, but in this case I use it):

npm install styled-components @types/styled-components

Imagine you want to create a list of elements and that the color of each element, as well as the cursor, changes when it is clicked on.

If the library is not used, this can be achieved by writing the following code, where I use a function to get the style using the component’s state (I write it directly in the index.tsx file for simplicity):

And the result, after clicking on the “Three” element, would be the following image:

If we used the library, you could replace the style function with a component that can interpolate a CSS fragment depending on the value of the “selected” property. The resulting code is as follows:

And the result, after clicking on the “Three” element, would be the following image:

The extension “vscode-styled-components” for Visual Studio Code is very useful to work with this library, because it adds syntax highlighting for templates and allows CSS autocompletion.

References:

--

--