Reader small image

You're reading from  Learn React with TypeScript - Second Edition

Product typeBook
Published inMar 2023
Reading LevelBeginner
PublisherPackt
ISBN-139781804614204
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Carl Rippon
Carl Rippon
author image
Carl Rippon

Carl Rippon has been in the software industry for over 20 years developing a complex lines of business applications in various sectors. He has spent the last 8 years building single-page applications using a wide range of JavaScript technologies including Angular, ReactJS, and TypeScript. Carl has also written over 100 blog posts on various technologies.
Read more about Carl Rippon

Right arrow

Approaches to Styling React Frontends

In this chapter, we will style the alert component we worked on in previous chapters using four different approaches. First, we will use plain CSS and understand the downsides of this approach. Then, we will move on to use CSS modules, which will resolve plain CSS’s main problem. We will then use a CSS-in-JS library called Emotion and a library called Tailwind CSS and will understand the benefits of each of these libraries.

We will also learn how to use SVGs in React apps and use them in the alert component for the information and warning icons.

We’ll cover the following topics:

  • Using plain CSS
  • Using CSS modules
  • Using CSS-in-JS
  • Using Tailwind CSS
  • Using SVGs

Technical requirements

We will use the following technologies in this chapter:

All the code snippets used in this chapter can be found online at https://github.com/PacktPublishing/Learn-React-with-TypeScript-2nd-Edition/tree/main/Chapter5.

Using plain CSS

We will start this section by setting up a React and TypeScript project with the alert component from Chapter 3, Setting Up React and TypeScript. Next, we will add the alert component from Chapter 3 and style it using plain CSS. Finally, we will look at one of the challenges with plain CSS and discover how we could mitigate it.

Creating the project

The project we will be using is the one we completed at the end of Chapter 3. This can be found at the following location: https://github.com/PacktPublishing/Learn-React-with-TypeScript-2nd-Edition/tree/main/Chapter3/Section2-Creating-a-project-with-Create-React-App/myapp. To copy this locally, carry out the following steps:

  1. Open Visual Studio Code in a folder of your choice.
  2. Run the following command in the terminal to clone the GitHub repository for the book:
    git clone https://github.com/PacktPublishing/Learn-React-with-TypeScript-2nd-Edition.git
  3. Reopen Visual Studio Code in the Learn-React-with-TypeScript...

Using CSS modules

In this section, we will learn about an approach to styling React apps called CSS modules. We will start by understanding CSS modules and then we will use them within the alert component that we have been working on.

Understanding CSS modules

CSS modules is an open source library available on GitHub at https://github.com/css-modules/css-modules, which can be added to the webpack process to facilitate the automatic scoping of CSS class names.

A CSS module is a CSS file, just like in the previous section; however, the filename has an extension of .module.css rather than .css. This special extension allows webpack to differentiate a CSS module file from a plain CSS file so that it can be processed differently.

A CSS module file is imported into a React component file as follows:

import styles from './styles.module.css';

This is similar to the syntax of importing plain CSS, but a variable is defined to hold CSS class name mapping information...

Using CSS-in-JS

In this section, we start by understanding CSS-in-JS and its benefits. We will then refactor the alert component we have used to implement CSS-in-JS and observe how it differs from CSS modules.

Understanding CSS-in-JS

CSS-in-JS isn’t a browser feature, and it isn’t even a specific library – instead, it is a type of library. Popular examples of CSS-in-JS libraries are styled-components and Emotion. There isn’t a significant difference between styled-components and Emotion – they are both popular and have similar APIs. We will use Emotion in this chapter.

Emotion generates styles that are scoped, similar to CSS modules. However, you write the CSS in JavaScript rather than in a CSS file – hence the name CSS-in-JS. In fact, you can write the CSS directly on JSX elements as follows:

<span
  css={css`
    font-weight: 700;
    font-size: 14;
  `}
>
 ...

Using Tailwind CSS

In this section, we will start by understanding Tailwind CSS and its benefits. We will then refactor the alert component we have been using to use Tailwind and observe how it differs from other approaches we have tried.

Understanding Tailwind CSS

Tailwind is a set of prebuilt CSS classes that can be used to style an app. It is referred to as a utility-first CSS framework because the prebuilt classes can be thought of as flexible utilities.

An example CSS class is bg-white, which styles the background of an element white – bg is short for background. Another example is bg-orange-500, which sets the background color to a 500 shade of orange. Tailwind contains a nice color palette that can be customized.

The utility classes can be used together to style an element. The following example styles a button element in JSX:

<button className="border-none rounded-md bg-emerald-700 text-white cursor-pointer">
  ...
</button...

Using SVGs

In this section, we will learn how to use SVG files in React and how to use them for the icons in the alert component.

Understanding how to use SVGs in React

SVG stands for Scalable Vector Graphics and it is made up of points, lines, curves, and shapes based on mathematical formulas rather than specific pixels. This allows them to scale when resized without distortion. The quality of icons is important to get right – if they are distorted, they make the whole app feel unprofessional. Using SVGs for icons is common in modern web development.

Create React App configures webpack to use SVG files when a project is created. In fact, logo.svg is referenced in the template App component as follows:

import logo from './logo.svg';
...
function App() {
  return (
    <div className="App">
      <header className="App-header">
      ...

Summary

In this chapter, we learned about four methods of styling.

First, we learned that plain CSS could be used to style React apps, but all the styles in the imported CSS file are bundled regardless of whether a style is used. Also, the styles are not scoped to a specific component – we observed the container CSS class names clashing with the App and Alert components.

Next, we learned about CSS modules, which allows us to write plain CSS files imported in a way that scopes styles to the component. We learned that CSS modules is an open source library pre-installed and pre-configured in projects created with Create React App. We saw how this resolved the CSS clashing problem but didn’t remove redundant styles.

Then, we discussed CSS-in-JS libraries, which allow styles to be defined directly on the React component. We used emotion’s css prop to style the alert component without an external CSS file. The nice thing about this approach is that conditional...

Questions

Answer the following questions to check what you have learned about React styling:

  1. Why could the following use of plain CSS be problematic?
    <div className="wrapper"></div>
  2. We have a component styled using CSS modules as follows:
    import styles from './styles1.module.css';
    function ComponentOne() {
      return <div className={styles.wrapper}></div>;
    }

We have another component styled using CSS modules as follows:

import styles from './styles2.module.css';
function ComponentTwo() {
  return <div className={styles.wrapper}></div>;
}

Will the styles of these div elements clash, given that they are using the wrapper class name?

  1. We have a component styled using CSS modules as follows:
    import styles from './styles3.module.css';
    function ComponentThree() {
      return <div className={styles.wrapper}>
    </div>
    }

The styles in styles3.module.css...

Answers

  1. The wrapper CSS class could clash with other classes. To reduce this risk, the class name can be manually scoped to the component:
    <div className="card-wrapper"></div>
  2. The CSS won’t clash because CSS modules will scope the class names to each component.
  3. The wrong class name is referenced in the component – it should be wrap rather than wrapper:
    import styles from './styles3.module.css';
    function ComponentThree() {
      return <div className={styles.wrap}>
    </div>
    }
  4. The css prop on the button could be as follows:
    <button
      css={css`
        border-radius: ${kind === "rounded" ? "4px" : "0px"};
      `}
    >
      ...
    </button>
  5. The style can be adjusted as follows to include the hover style:
    <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
      ...
    </button
  6. Logo...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn React with TypeScript - Second Edition
Published in: Mar 2023Publisher: PacktISBN-13: 9781804614204
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 $15.99/month. Cancel anytime

Author (1)

author image
Carl Rippon

Carl Rippon has been in the software industry for over 20 years developing a complex lines of business applications in various sectors. He has spent the last 8 years building single-page applications using a wide range of JavaScript technologies including Angular, ReactJS, and TypeScript. Carl has also written over 100 blog posts on various technologies.
Read more about Carl Rippon