Three Flavors of React CSS

Leverage the multiple ways of using CSS in React

Tenji Tembo
5 min readFeb 9, 2018

ReactJS is one of the most popular frameworks according to Stack Overflow. It’s declarative based design allows for programmers to create simple views with very minimal code, allowing React to efficiently manage the various states your app enters during it’s lifecycle. We can style a React component in a number of ways, and depending on the implementation each style brings something to the table that reinforces React’s ease of use. Inline, Component-based styling, and CSS Preprocessors are three popular options, since each offer a solution to that scale of a problem.

Inline

Inline Styling is the most direct way to inject CSS into a singular component. It’s only applied to that component, and will not be affected by any other external style sheets, provided there is nothing like !important overrides present. To style an inline component it’s as easy as injecting it into the HTML:

function myInlineComponent() {
return (
<div style={{color: 'red', fontSize: '12'}}>
Hello World!
</div>
);
}

This is fine for simply adding some basic styling to a singular component. In applications where React is added for a single function or element of a page, and isn’t subject to the rest of the application, this works just fine. There is no need to import multiple external packages, or engage in more complex solutions such as linking a preprocessor. If the React code remains contained, the accompanying CSS can as well. Depending on the rendered HTML, external style sheets can assist in adding a bit more flair, but aren’t required to be imported to the component itself. This further isolates the code, allowing it to simply be declared in other parts of the repository.

Component Styling

Component Styling takes inline styling to the next level, allowing for more complex solutions to take fruit in the same smaller applications. These ease the maintenance of multiple style declarations, by keep the code in a easy to read form, while allowing for easy readability and troubleshooting. There are two ways to perform “Component CSS”.

First, is by housing the CSS inside of the module itself. We create a CSS as a constant inside of the component:

const divStyle = {
color: 'red',
fontSize: '12',
fontFamily: 'Helvetica Neue',
};

With this we can simply add the style back to the component:

return <div style={divStyle}>Hello World!</div>;

This is fairly extensible for flat level styling. Any of common CSS properties used are available to use in the declaration of the stylesheet. This include CSS3 properties such as border-image-repeat, background-clip, and more. Where this falls apart, are the more advanced techniques in CSS. We’re taking pseudo-selectors such as :hover or :nth-child, vendor prefixing, and media queries. These nested selectors don’t usually translate well to this implementation, and require the use of external packages and/or CSS preprocessors. And this is where Preprocessors come to save the day :)

CSS Modules & Preprocessors in React

Before I begin preaching to the choir about the benefits of Preprocessors, let’s back peddle a bit and talk about Preprocessors and CSS Modules in general. A Preprocessor is a computer program that modifies data to conform with the input requirements of another program. Common examples include LESS, SASS, and CPP. In our case, it’s using these programs to leverage tech like variables, mixins, media queries, and functions, to have it translated to CSS3 compatible code for webpages to render. We can even minify the result to save on file size, which is good for mobile and load times.

A CSS Module is a CSS file in which all class and animation names are scoped locally by default. This reduces potential conflicts, allows explicit dependencies, and eliminates any need for global scope declarations. When you load a CSS Module into a component, a unique name is generated for each CSS selector referenced in the component; known as Interoperable CSS. CSS Modules play nice with Preprocessors, allowing the usage of tech such as variables, via certain packages like PostCSS-ICSS-Values.

To use CSS Modules in React, it’s as simple as installing the react-css-modules package and importing the CSS to the file as below:

import React from 'react'
import CSSModules from 'react-css-modules'
import styles from './main.css'

class App extends React.Component {
render() {
return (
<button styleName='button primary'>
Sign Up
</button>
);
}
}

export default CSSModules(App, styles, {allowMultiple: true});

Note: be sure to wrap the export in CSSModules in order to use the target CSS file when rendering.

So how does this help us in the long term? By combining the extensibility of preprocessors to create custom CSS declarations similar to the snippet below:

@import './variables.scss';

.super-class {
.sub-class {
&:nth-child {
&:active, &:hover {...}
}
&:first-child{...}
}
}

We can utilize the benefits of imports, pseudo-selectors, media queries, and more in a manageable, extensible, and sectioned off part of code. This makes it really simple for scenarios such as UI Light/Dark themes, or responsiveness support.

Bonus: CSS-in-JS

CSS-in-JS is newly utilized method for adding complex CSS to JSX components. Through various packages created by the react community, we can reap the same benefits CSS3 offers, but keeps code localized in a manner similar to CSS Modules. For example, React CSS Components by Andrey Popp allows for CSS to be defined using React Components rather than the traditional CSS lingo of HTML tags and classes. The big benefit to most of these “CSS in JS” packages is extending real logic to CSS behavior. Whether it’s emotion usage of styling based on props, or cssobj dynamically rendering based on server side behavior, options are abound for real complex usage in CSS.

To wrap this up

There are different solutions for each use case of CSS in React. And they all contribute to react’s overall philosophy: declarative, component based design. We can make our lives simple by implementing inline styles, but are subject to a small scope. We can introduce a bit of variety and depth with Component Styling, while also improving readability, yet we can’t leverage more complex tech such as responsiveness.

CSS Modules and CSS-in-JS do require a significant amount of buy-in, and can be overkill depending on the complexity of the project. But the benefits that CSS Modules can bring to an application, as well as it’s ability to scale well with larger scopes, makes it a viable solution for any React project.

Thanks for reading! This post is more gear towards people starting out in ReactJS (looking at you CODE2040 Class of 2018), in order to clue you in on some things to think about when learning about the wonderful world of JavaScript. But that doesn’t you can’t learn something new too :)

Be sure to drop a clap below, and follow Lovable Technology and Tenji Tembo on Twitter for more

--

--