Different ways to write CSS in React | CSS tips

Posted on

We all know the standard way to bind a stylesheet to the <head> of an HTML document, right? This is just one of the many ways we can write CSS. But what does it look like to style things in a single page application (SPA), for example in a React project?

It turns out that there are several ways to style a React app. Some overlap with the traditional style, others less so. But let’s count all the ways we can do it.

Importing external style sheets

As the name suggests, React can import CSS files. The process is similar to how we link the CSS file in the HTML <head>:

  1. Create a new CSS file in your project directory.
  2. Write CSS.
  3. Import it into the React file.

Like that:

import "./style.css";

This usually goes to the top of the file where other imports occur:

import { React } from "react";
import "./Components/css/App.css";
function App() {
  return (
    <div className="main">
    </div>
  );
}
export default App;

In this example, a CSS file is imported into a App.js from /Components/css case.

Write inline styles

You might be used to hearing that inline styling isn’t so good for maintainability and so on, but there are definitely situations (here’s one!) where it makes sense. And maintainability is less of an issue in React, since the CSS is often already in the same file anyway.

Here’s a super simple example of inline styling in React:

<div className="main" style={{color:"red"}}>

A better approach, however, is to use objects:

  1. First, create an object containing styles for different elements.
  2. Then add it to an element using the style attribute and then select the property to style.

Let’s see this in context:

import { React } from "react";
function App() {
  const styles = {
    main: {
      backgroundColor: "#f1f1f1",
      width: "100%",
    },
    inputText: {
      padding: "10px",
      color: "red",
    },
  };
  return (
    <div className="main" style={styles.main}>
      <input type="text" style={styles.inputText}></input>
    </div>
  );
}
export default App;

This example contains a styles object containing two other objects, one for the .main class and the other for text input, which contain style rules similar to what we expect to see in an external style sheet. These objects are then applied to the style attribute of the elements that are in the returned markup.

Note that braces are used to reference styles rather than the quotes we would normally use in plain HTML.

Use CSS modules

CSS modules…what happened to them, right? They benefit from locally scoped variables and can be used with React. But what are they, again, exactly?

Quoting the deposit documentation:

CSS modules work by compiling individual CSS files into CSS and data. The CSS output is normal global CSS, which can be injected directly into the browser or concatenated and written to a file for production use. The data is used to map the human readable names you used in the files to the globally safe output CSS.

In simpler terms, CSS modules allow us to use the same class name in multiple files without conflicts since each class name is given a unique programming name. This is especially useful in large applications. Each class name is locally restricted to the specific component it is imported into.

A CSS module stylesheet is similar to a regular stylesheet, but with a different extension (e.g. styles.module.css). Here is how they are configured:

  1. Create file with .module.css as an extension.
  2. Import this module into the React application (as we saw earlier)
  3. Add one className to an element or component and reference the particular style from the imported styles.

Very simple example:

/* styles.module.css */
.font {
  color: #f00;
  font-size: 20px;
}

import { React } from "react";
import styles from "./styles.module.css";
function App() {
  return (
    <h1 className={styles.heading}>Hello World</h1>
  );
}
export default App;

Use styling components

Did you use styling components? It is quite popular and allows you to create custom components using actual CSS in your JavaScript. A styled component is basically a React component with – get ready – styles. Some of the features include unique class names, dynamic styling, and better CSS handling as each component has its own distinct styles.

Install the npm styled-components package in the command line:

npm install styled-components

Then import it into the React application:

import styled from 'styled-components'

Create a component and assign a style property to it. Note the use of template literals indicated by backticks in the Wrapper object:

import { React } from "react";
import styled from "styled-components";
function App() {
  const Wrapper = styled.div`
    width: 100%;
    height: 100px;
    background-color: red;
    display: block;
  `;
  return <Wrapper />;
}
export default App;

What precedes Wrapper The component will be rendered as a div containing these styles.

Conditional styling

One of the benefits of styling components is that the components themselves are functional, because you can use props in the CSS. This opens the door to conditional statements and changing styles based on a state or accessory.

Here is a demo showing this:

Here we manipulate the div’s display property on view state. This state is controlled by a button that toggles the state of the div when clicked. This, in turn, toggles between the styles of two different states.

On line if statements, we use a ? instead of the usual if/else syntax. The else part is after the semicolon. And remember to always call or use state after it’s initialized. In this last demo, for example, the state must be above the Wrapper component styles.

Good React hairstyle!

It’s a wrap, folks! We looked at several different ways to write styles in a React application. And it’s not like one is better than the other; the approach you use depends on the situation, of course. Hopefully by now you understand them well and know that you have a bunch of tools in your React style arsenal.

Leave a Reply

Your email address will not be published.