Reader small image

You're reading from  React 18 Design Patterns and Best Practices - Fourth Edition

Product typeBook
Published inJul 2023
Reading LevelExpert
PublisherPackt
ISBN-139781803233109
Edition4th Edition
Languages
Tools
Right arrow
Author (1)
Carlos Santana Roldán
Carlos Santana Roldán
author image
Carlos Santana Roldán

Carlos Santana Roldán is a senior web developer with more than 15 years of experience. Currently, he is working as a Principal Engineer at APM Music. He is the founder of JS Education, where he teaches people web technologies such as React, Node.js, JavaScript, and TypeScript.
Read more about Carlos Santana Roldán

Right arrow

Making Your Components Look Beautiful

Our journey into React best practices and design patterns has now reached the point where we want to make our components look beautiful. To do that, we will go through all the reasons why regular CSS may not be the best approach for styling components, and we will check out various alternative solutions.

Starting with inline styles, then CSS modules, and styled-components, this chapter will guide you through the magical world of CSS in JavaScript.

In this chapter, we will cover the following topics:

  • Common problems with regular CSS at scale
  • What it means to use inline styles in React and their downsides
  • How to set up a project from scratch using Webpack and CSS modules
  • Features of CSS modules and why they represent a great solution to avoid global CSS
  • styled-components, a new library that offers a modern approach to styling React components

Technical requirements

To complete this chapter, you will need the following:

  • Node.js 19+
  • Visual Studio Code

You can find the code for this chapter in the book’s GitHub repository: https://github.com/PacktPublishing/React-18-Design-Patterns-and-Best-Practices-Fourth-Edition/tree/main/Chapter06.

CSS in JavaScript

In November 2014, Christopher Chedeau, also known as vjeux, gave a talk at the NationJS conference (https://blog.vjeux.com/2014/javascript/react-css-in-js-nationjs.html) that sparked a revolution in the way React components are styled. As a contributor to React and an employee of Meta, Christopher outlined the many issues Facebook faced with CSS at scale. Understanding these issues is important because they are common in web development and will help us introduce concepts such as inline styles and locally scoped class names.

The following is a list of the issues with CSS, which are basically problems with CSS at scale:

  • Global namespace
  • Dependencies
  • Dead code elimination
  • Minification
  • Sharing constants
  • Non-deterministic resolution
  • Isolation

The first well-known problem of CSS is that all the selectors are global. No matter how organized our styles are by using namespaces or a procedure such as the Block, Element...

Understanding and implementing inline styles

The official React documentation suggests developers use inline styles to style their React components. This seems odd because we all learned in past years that separating the concerns is important and we should not mix markup and CSS.

React tries to change the concept of separation of concerns by moving it from the separation of technologies to the separation of components. Separating markup, styling, and logic into different files when they are tightly coupled and where one cannot work without the other is just an illusion. Even if it helps keep the project structure cleaner, it does not give any real benefit.

In React, we compose components to create applications where components are a fundamental unit of our structure. We should be able to move components across the application, and they should provide the same result regarding both logic and UI, no matter where they get rendered.

This is one of the reasons why collocating...

Using CSS modules

If you feel that inline styles are not a suitable solution for your project and your team, but you still want to keep the styles as close as possible to your components, there is a solution for you, called CSS modules. The CSS modules are CSS files in which all class names and animation names are scoped locally by default. Let’s see how we can use them in our projects; but first, we need to configure webpack.

Webpack 5

Before diving into CSS modules and learning how they work, it is important to understand how they were created and the tools that support them.

In Chapter 3, Cleaning Up Your Code, we looked at how we can write ES6 code and transpile it by using Babel and its presets. As soon as the application grows, you may want to split your code base into modules as well.

You can use Webpack or Browserify to divide the application into small modules that you can import whenever you need them, while still creating a big bundle for the browser...

Setting up a project

In this section, we will look at how to set up a very simple Webpack application, using Babel to transpile the JavaScript and CSS modules to load our locally scoped CSS into the bundle. We will also go through all the features of CSS modules and look at the problems they can solve. The first thing to do is move to an empty folder and run the following command:

npm init

This will create a package.json file with some defaults.

Now, it is time to install the dependencies, with the first one being Webpack and the second being webpack-dev-server, which we will use to run the application locally and to create the bundle on the fly:

npm install --save-dev webpack webpack-dev-server webpack-cli

Once Webpack is installed, it is time to install Babel and its loader. Since we are using Webpack to create the bundle, we will use the Babel loader to transpile our ES6 code within Webpack itself:

npm install --save-dev @babel/core @babel/preset-env ...

Locally scoped CSS

Now it is time to create our app, which will consist of a simple button of the same sort we used in previous examples. We will use it to show all the features of the CSS modules.

Let’s update the src/index.tsx file, which is the entry we specified in the Webpack configuration:

import { createRoot } from 'react-dom/client'

We can then create a simple button. As usual, we are going to start with a non-styled button, and we will add the styles step by step:

const Button = () => <button>Click me!</button>

Finally, we can render the button into the DOM:

createRoot(document.getElementById('root') as HTMLElement).render(<Button />)

Now, suppose we want to apply some styles to the button – a background color, size, and so on. We create a regular CSS file, called index.css, and we put the following class into it:

.button {
  background-color: #ff0000;
  width: 320px;
  padding: 20px...

Implementing styled-components

There is a library that is very promising because it takes into account all the problems other libraries have encountered in styling components. Different paths have been followed for writing CSS in JavaScript, and many solutions have been tried, so now the time is ripe for a library that takes all the learning and then builds something on top of it.

The library is conceived and maintained by two popular developers in the JavaScript community: Glenn Maddern and Max Stoiber. It represents a very modern approach to the problem, and it uses the edge features of ES2015 and some advanced techniques that have been applied to React to provide a complete solution for styling.

Let’s look at how it is possible to create the same button we saw in the previous sections and check whether all the CSS features we are interested in (for example, pseudo-classes and media queries) work with styled-components.

First, we have to install the library by...

Summary

In this chapter, we explored important topics that aim to help readers navigate the complexities of styling in React. We discussed the challenges of scaling CSS, using Meta’s experiences as examples to highlight the real-world difficulties faced by large organizations. This emphasizes the relevance and applicability of the knowledge we’re sharing.

To make styling in React more intuitive and efficient, we examined how inline styles work and the benefits of co-locating styles within components. This approach promotes organized and readable code, which is crucial for developers aiming to master React.

Recognizing the limitations of inline styles, we introduced CSS modules as an alternative. We provided a step-by-step guide to setting up a project, allowing readers to learn through hands-on experimentation.

Importing CSS files into components was also emphasized as an important practice. This helps clarify dependencies and prevents issues by keeping class...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React 18 Design Patterns and Best Practices - Fourth Edition
Published in: Jul 2023Publisher: PacktISBN-13: 9781803233109
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime

Author (1)

author image
Carlos Santana Roldán

Carlos Santana Roldán is a senior web developer with more than 15 years of experience. Currently, he is working as a Principal Engineer at APM Music. He is the founder of JS Education, where he teaches people web technologies such as React, Node.js, JavaScript, and TypeScript.
Read more about Carlos Santana Roldán