4 Ways To Style Your React Components

React + CSS

So you’ve built your first React Component but don’t know how to style it. Well, here are 4 quick ways to style your Component and get things running up quickly:

  1. Vanilla CSS

Just like you would style a regular HTML page by linking a CSS file using a link element or tag, you can add CSS styling to your React Component by using the import keyword like so:

So for example, let’s say you have a React Component like so:

Your CSS would be like a regular CSS file:

It is assumed that the CSS file is in the same location (directory) as your React Component.

2. Style Objects

Another way to add styling to your React Component is by setting the Style property of your Component to a Style Object. A Style Object is a simple JS object that defines a set of key, value pairs of CSS properties (this looks very similar to your CSS file).

Style Objects are useful when you want to dynamically change the CSS styling properties on your component based on some prop or state change.

A typical JavaScript Style Object would look like so:

You could add this to your React Component like so:

This can also be written inline like so:

via the Style property of your Component. You can use a JavaScript Style object to define a set of key, value pairs of CSS properties.

3. CSS Modules

CSS Modules are simply CSS files that help you define CSS class names in a local scope in order to avoid style conflicts with previous class definitions of the same name.

I explained more about this in detail here.

Using CSS Modules helps us avoid conflicting class names like so:

Let’s assume your button.module.css file is like so:

You can now import this file into your React button like so:

The beauty of CSS Modules is that we can use exact CSS class names for many different Components and never have to worry about conflicts.

This is possible because, at the granular level, the CSS module compiler (Webpack) converts each class name to a unique name using a hash function and stores them in a styles object.

So for example, two different components (making use of a button element and anchor element respectively) with the same class name would end up looking like this when outputted to our web page.


4. Styled Components

This is by far one of the most popular ways of adding CSS styling to most React Components. It basically involves you writing CSS directly in your React Component like so:

Now your component can be used further with the styling added to it like so:

Full Stack Engineer