Borrowed from Optimizing React by Evil Martians © copyright 2018

React CSS for Beginners

Part II of a III part series: How to style your React projects

Llamacorn

--

Facebook developed React.js which is an open source JavaScript library used to create awesome user interfaces for the web. In my previous article I talked about React basics. In this article we’ll go a little deeper, and talk about what makes this library great for developing beautiful, maintainable user interfaces. It should be known that I don’t work for Facebook, and this article is not a shameless plug to keep my job 😂. I wrote it as I was learning to use React in hopes to help others decide whether they want to invest the time to learn it.

Why is React so popular?
First of all, React’s UIs load super fast without compromising a great experience for the user. In React, you can set different views for each component or the entire app based on its state. React’s library changes only the necessary parts instead of reloading the entire app. So now that I’ve mentioned why you might want to consider React, let’s talk about how to make your interface look great 🤩.

How to Style React Components
Styling in React is a little different than styling in a traditional web development. You can add your style inline with your HTML, import your stylesheets into the head tag of your HTML file, or you can use CSS modules. I’ll go into more detail about the differences below.

Image from LinkedIn posted by Scott Fegette 2015

In case you are new to web development, I’ll explain a bit about CSS. Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation of a document written in a markup language like HTML.[1] CSS is a cornerstone technology of the World Wide Web, alongside HTML and JavaScript.[2]

CSS was created to allow for the separation of presentation and content, including layout, colors, and fonts.[3] This separation improves maintainability of the content, and provides more flexibility and control in the presentation layer. It also allows for multiple web pages to use the same formatting by specifying the relevant CSS in a separate .css file, and it reduces complexity and repetition in the structural content. We all know DRY code is preferable.

Inline Styling
Inline styling is generally considered bad practice. Some reasons why you might want to implement your style this way is that inline styles take precedence over all other styles. Even so, it is still not a good idea. Some reasons why:

  1. Writing code isn’t just about how long it takes to load, it’s also about readability. Inline CSS goes into the HTML tag, and there isn’t really a way to arrange it with your HTML to make it easy to read through unless you’re using only a couple inline attributes 🤯.
  2. Inline CSS is really not a good idea when working on projects with more than one page because it takes a lot of time to update. For example, if you need to change the color or size of something that is styled inline, you have to do it for every page 🐌; whereas if you used an external CSS file, you just change it once and be done 🏎.

In React, since your components are usually pretty compact, adding a few inline styles is considered ok. Preferable even, if you’re only adding a few styles, or the component is pretty simple. React is already managing the state of your components, this makes styles of state and behavior a natural fit for colocation with your component logic.

Since the main purpose of the inline style attribute is for dynamic, state based styles, you could have a width style on a progress bar based on some state, or the position or visibility based on something else.

Simple components with inline CSS

Things to note, when using inline styles in React you have to pass them in as objects. If the property name is usually kabob cased, change it to camel case. Don’t worry if you forget this, the browser will let you know 😎.

Inline vs stylesheet, and which takes precedence.

CSS Stylesheet
With a traditional web app architecture, you will use a single css file to style your html file. However, since React uses components, you can simply import the .css file that is relevant to the component. When you import the component into a parent component, all the styles stay with the component and do not cascade down to child components.

Here is a sample component to style with CSS stylesheet.

import React from 'react'; 
import './DottedBox.css';
const DottedBox = () => (
<div className="dotted-box">
<p className="dotted-box-content">
My styling with CSS stylesheet
</p>
</div>
);
export default DottedBox;

And the corresponding CSS in a file called DottedBox.css. You might take note of my use of CSS variables. I use this strategy for making the colors and sizes easier to update. If I keep them at a root level, then I can change the color in one place, and it’s faster to make slight adjustments, get feedback from the design team, and adjust as needed.

:root {
--charcoal-color: #282c34;
--dark-grey: #4A4A4A;
}
.dotted-box {
margin: 2rem;
border: 3px dotted var(--dark-grey);
}
.dotted-box-content {
font-size: 1rem;
text-align: center;
}

CSS modules
According to the repo, CSS modules are:
CSS files in which all class names and animation names are scoped locally by default.

This basically means that CSS Modules are not an official specification or an implementation in the browser. Instead its a process in the build step using Webpack or Browserify that changes class names and selectors to be scoped (i.e. kinda like namespaced).

What does this look like and why do it? We’ll get to that in a sec. First, remember how HTML and CSS normally work. A class is applied in HTML

<h1 class="title">The Best Title in the Hello World</h1>

Styling it in CSS would look like

.title {
background-color: blue;
}

As long as that CSS is applied to the HTML document in the <head>, the background of that <h1> would be blue. We don't need to process the CSS or the HTML. The browser understands both those file formats.

CSS Modules takes a different approach. Instead of writing plain HTML, we need to write all of our markup in a JavaScript file, like index.js. Here’s an example of how that might work.

import styles from "./styles.css; element.innerHTML=`<h1 class="${styles.title}">
An Awesome Title
</h1>`;

During the build phase, the compiler would search through that styles.css file that we’ve imported, then look through the JavaScript we’ve written and make the .title class accessible via styles.title. The build step would then process both these things into new, separate HTML and CSS files, with a new string of characters replacing both the HTML class and the CSS selector class.

Our generated HTML might look like

<h1 class="_styles_title_309571057">
An Awesome Title
<h1>

Our generated CSS might look like

.styles_title_309571057 { background-color: blue; }

The class attribute and selector .title is gone and replaced by an completely new string. The original CSS is not being served to the browser.

As Hugo Giraudel said in his tutorial on the subject
[the classes] are dynamically generated, unique, and mapped to the correct styles.

This is what is meant by styles being scoped. They are scoped to particular templates. If we have a buttons.css file we would import it only into abuttons.js template and a .btn class within would be inaccessible to some other template (e.g. forms.js), unless we imported it there as well.

What is the benefit of using CSS Modules?
With CSS Modules, it’s a guarantee that all the styles for a single component:

  1. Live in one place
  2. Only apply styling to that component only

Plus, any component can have a true dependency, like:

import buttons from "./buttons.css"; 
import padding from "./padding.css";
element.innerHTML = `<div class="${buttons.red} ${padding.large}">`;

Styled-components
What are the benefits of creating styled components?

Styled-components are the result of wondering how React developers could enhance CSS for styling components. With focusing on a single use case it optimizes the experience for developers as well as the output for end users. As a developer, ease of use and efficiency are the main reasons I love working with React.

Apart from the improved experience for developers, styled-components provide…

  • Automatic critical CSS: styled-components keeps track of which components are rendered on a page and injects their styles and nothing else, fully automatically. Combined with code splitting, this means your users load the least amount of code necessary.
  • No class name bugs: styled-components generates unique class names for your styles. You never have to worry about duplication, overlap or misspellings.
  • Easier deletion of CSS: it can be hard to know whether a class name is used somewhere in your codebase. styled-components makes it obvious, as every bit of styling is tied to a specific component. If the component is unused (which tooling can detect) and gets deleted, all its styles get deleted with it.
  • Simple dynamic styling: adapting the styling of a component based on its props or a global theme is simple and intuitive without having to manually manage dozens of classes.
  • Painless maintenance: you never have to hunt across different files to find the styling affecting your component, so maintenance is a piece of cake no matter how big your codebase is.
  • Automatic vendor prefixing: write your CSS to the current standard and let styled-components handle the rest.

You get all of these benefits while still writing the CSS you know and love, just bound to individual components.

When to use which type of styling?
Now that you have been exposed to the different methods of styling, you now have a better picture of each use case. Basically, choosing the best styling will come down to a few factors.

  1. What is your time budget?
  2. What is your personal preference?
  3. Which solution will be most maintainable for future you? Will you remember that you used inline styles on a component one year from now? Or will someone else be able to find the styles without too much direction from you if you move on to other work?

Conclusion
Thank you for reading this article about the different ways to style CSS. If you are curious and want to try out each type, I recommend checking out these awesome tutorials to help you get some practice with each method.

https://github.com/MakeSchool-Tutorials/web-7-react-redux-passwords-app
https://github.com/MakeSchool-Tutorials/web-7-react-redux-timers-app
https://github.com/MakeSchool-Tutorials/web-7-react-redux-tetris-app

Happy coding! 🤓🤖👾

--

--