9 Ways To Implement CSS in React JS

Dmitry Nozhenko
8 min readAug 5, 2019

--

Hey, guys. Today I want to tell you about css in React app. So it was that styles are very important around in web. There are no sites that look good without css.

Many developers and companies do not pay enough attention to styles. Of course if you are javascript (react) developer you would like to create more javascript logic and spend less time with styles. Or your team has special people who create styles. However this way may be dangerous for you. I came all this way and I stopped writing the styles two years ago. So now I only focus on javascript and react. But, it’s time to think about css in react. I hope this topic could be helpful for many developers.

I picked 9 popular ways to implement css in react

  1. Standard CSS
  2. Inline CSS
  3. CSS Modules
  4. Preprocessors SASS, less, styles, etc
  5. Styled Components
  6. Aphrodite
  7. Radium
  8. JSS
  9. Emotion

I styled one component with each method. It has a wrapper, a title and a button. 👇👇👇

……………………………..……………………….👇
You can find all source code in my GitHub, click here. 👈
……………………………..………………………👆

1. Standard CSS

You’ll need to install css-loader and style-loader if you use a custom webpack build.

npm install css-loader, style-loader --save-dev

The next step is adding loaders to a webpack config.

module.exports = {
module: {
loaders: [{
test: /\.css$/,
loader: "style-loader!css-loader"
}]
}};

After writing a standard css file and importing it in a react file.

import "styles.css";

It should be enough for the styles to work.

Take a look at how webpack loaders work, how they get your css and add it to the head html tag with wrapped tags style.

<style type="text/css">
body {
background: red;
}
</style>

If you use create-react-app, css should work out of the box without loaders.

2. Inline CSS.

Inline css isn’t the best way to implement css in app. But sometimes, it is useful. This way is similar to the old way of using styles in HTML documents. In react js, inline styling is a little bit different. There are two ways you can implement it:

  • Passing Stylesheet properties in the component (component: Title)
  • Defining Stylesheet blocks are similar to classes in css (components: Wrapper, Button👇)

Be careful with inline styles.

3. CSS Modules

CSS module is a different approach to include CSS in React Apps. CSS modules turn CSS into the local scope which means that the CSS scoped to that particular component and the file.

CSS modules generate styles dynamically for a particular component. Here is an example of generated CSS by CSS Modules.

Pay attention to css filename ${your_name}.module.css - this is required.

If you create a file name without this rule that your styles won’t work. Css file looks like as a regular css, without a magic 🧙‍♂️.

CSS Components is useful tool for isolated components.

4. Preprocessors SASS / LESS

Preprocessors are powerful tools if you know how it use. I’m a proponent of sass. Developers behind ‘sass’ describe it as: “Sass is the most mature, stable, and powerful professional grade CSS extension language in the world.” — So, let’s see how to integrate sass in react.

Sass / Scss:

  1. Install npm loaders:
npm install style-loader css-loader sass-loader --save-dev

2. Create a rule in s webpack config

rules: [{    
test: /\.scss$/,
use: [
'style-loader', // creates style nodes from JS strings
'css-loader', // translates CSS into CommonJS
'sass-loader' // compiles Sass to CSS, using Node Sass by default
],
}]

This is a base webpack config for sass. I took it from the official documentation. You can see here.

You could use sass/scss files in your app after modifying a configuration. The importing sass file works as well as css.

import './style.scss';

Also plenty of developers prefer to use less preprocessor. You can see how to integrate less in react below.👇

Less:

  1. Install npm loaders:
$ npm install style-loader css-loader less-loader --save-dev

2. Create rule in a webpack config:

module.exports = {
module: {
rules: [
{
test: /\.less$/,
use: [
{
loader: 'style-loader', // creates style nodes from JS strings
},
{
loader: 'css-loader', // translates CSS into CommonJS
},
{
loader: 'less-loader', // compiles Less to CSS
},
],
},
],
},
};

This is a base webpack config for less. If you want learn more click here. So as you see, the steps for integration preprocessors in ReactJs application are similar. Also the importing in app works like css and sass.

If you want to use stylus or postCss you’ll try to integrate them on the links below 👇

We considered popular ways of creating styles in react with css and preprocessors.

Next part of this article is about css in js.

👨‍💻 So, let’s get started

CSS in JS

CSS in JavaScript provides a new playground for the stylesheet. When we talk about CSS, you might start thinking about tag base selectors, class selectors or id selectors.

But with the help of CSS-in-JS, you can have all abilities to structure and to think on component level instead of the document. You don’t need to maintain more CSS files, instead of it, you can style CSS using Javascript. You have all javascript power to work with CSS. There are a lot of CSS-in-JS libraries that you could use in your project. We are about to discuss some of them, let’s begin 👇

5. Styled Components

Styled Components is one of the most popular CSS-in-JS library presented at Github. It has 23K+ stars on GitHub.

Styled-components is a powerful library. It has a plenty of features, for example: “Existing CSS, Passed props, Animations, Server Side Rendering, Media Templates, Security, Theming”, and support for React Native, TypeScript and others. You may find their documentation here.

In order to use this library in a project, you should install it. Type a command as indicated below. 👇

npm install --save styled-components

To make use of this code for import style-component into your JS File as shown below👇

import styled from 'styled-components';

It’s time to check how it looks 🔍

As you can see we created components based on styles from styled-components npm package. You can use styled with method div or other html tags.

6. Aphrodite

One more CSS in JS library with 4,7K+ ⭐️ is on GitHub. According to Aphrodite developers, it is one of the best-suited library for React JS. It supports the pseudo code as well as the media queries, that are necessary in responsive design. It adds CSS at the time of rendering components inside DOM according to developers.

How to install Aphrodite?

npm install --save aphrodite

So, let’s check how it works 👀

This way is similar to styled-components and inline style.

7. Radium

This CSS-in-JS library focuses on inline styling and dead code elimination which would be useful. Radium is a very popular library with more than 6.9K ⭐️ on GitHub.

It has supports for:

  • Inline styles
  • Pseudo Selector hover, active, focus, ...
  • Media queries
  • vendor prefixing
  • Animation
  • ES6 class
  • createClass

It is a short guide how to use it in React Application:

npm install -s radium

So let me just show a clear example

🚨 Please, notice the creation of the component and wrapping it with Radium function.

8. JSS (react-jss)

JSS is one more library with more that 5k stars on GitHub. There are several reasons to use JSS library:

Why should you use JSS library instead of other?

  • Declarative
  • Conflict-free and reusable
  • JSS can compile in the browser
  • It also supports server-side rendering since it the opportunity to compile at build time in Node
  • JSS is more than a CSS-in-JS library. You could use it as the simplest format as well as other CSS-in-JS Libraries like styled-component
  • You can use the preprocessors with JSS libraries like SASS, LESS, etc
  • Modularity
  • Dead Code Elimination

Install this package like in examples of the above-described

npm install --save react-jss

An example:

As you see, we have const with styles and a functional component. After importing injectSheet and calling it with styles and component.

injectSheet(styles)(Jss)

9. Emotion

This CSS library is focused on the application performance. With more than 7.7K ⭐️ on GitHub it is one of the most popular CSS-in-JS libraries. Emotion provides a powerful and a predictable style composition in addition to a great developer experience with features such as source maps, labels, and testing utilities. Both string and object styles are supported.

Let’s do a quick setup:

npm install --save @emotion/core

Check the example below to understand how to use emotion:

Emotion has a similar syntax to like a styled-components

Pay attention to the comment on the top of file line

/** @jsx jsx */

If you don’t use this line, “Emotion” won’t work.

🏁 Conclusion

Today we’ve explored 9 ways of adding styles in ReactJs application. You can find all source code in my GitHub. Fork and enjoy. I will be happy if you follow me and give star ⭐️ ❤️

I want to underline, each of these methods has its own audience. If you decide to use one of ways, don’t ignore others. Creating proper architectures you could use any ways, except inline styles 😄

I prefer to use styled-component, but also I use sass for styles with methodology BEM. It would be ok to highlight these two libs classnames and bem-classnames for this task.

I’m really hoping that the article will be useful for you. Let me know in comments, if you decide to deal with new libs for styles.

And remember, the styles are so important. Be careful 😄

👇 Don’t miss these articles 👇

1. 5 Ways to animate a React app in 2019 — 🧙‍♂️

2.Tracking Errors In React App With Sentry — ⚠️

❤️ Thanks for Reading

Have fun, keep learning, and always keep coding. Follow me on Medium & Linkedin.

👏 Like, Share, Leave your comment

If you have any questions or feedback, let me know in the comments below 👇

📖 📖 📖 Javascript and React Books 📖 📖 📖

  1. The Road to learn React
  2. Learning React: Functional Web Development with React and Redux
  3. Eloquent JavaScript, 3rd Edition: A Modern Introduction to Programming
  4. JavaScript: The Definitive Guide: Activate Your Web Pages (Definitive Guides)
  5. React Quickly: Painless web apps with React, JSX, Redux, and GraphQL
  6. JavaScript: The Good Parts
  7. JavaScript Patterns: Build Better Applications with Coding and Design Patterns

--

--