Dynamically add CSS classes to Elements in React


Borislav Hadzhiev

Last updated: May 2, 2022


Photo from Unsplash

Dynamically add CSS classes to Elements in React #

Use a template literal to dynamically add CSS classes to React elements. Template literals are delimited with backticks and allow us to embed variables and expressions using the dollar sign and curly braces ${expression} syntax.

import {useState} from 'react'; import './App.css'; export default function App() { const [isActive, setIsActive] = useState(false); const handleClick = event => { // 👇️ toggle isActive state variable setIsActive(current => !current); }; const myClass = 'bg-salmon'; return ( <div> <div className={`text-white ${myClass}`}>Hello world</div> <br /> <button className={`font-lg ${isActive ? 'bg-salmon text-white' : ''}`} onClick={handleClick} > Click </button> </div> ); }

And here is the CSS for the example.

.bg-salmon { background-color: salmon; } .text-white { color: white; } .font-lg { font-size: 2rem; padding: 10px 10px; }

add class dynamically

We can use a template literal to concatenate a string and a variable when setting classes.

Note that the string is enclosed in backticks ``, not in single quotes.

The dollar sign and curly braces syntax allows us to use placeholders that get evaluated.

<div className={`text-white ${myClass}`}> Hello world </div> <button className={`font-lg ${isActive ? 'bg-salmon text-white' : ''}`} onClick={handleClick} > Click </button> <div className={`text-white ${'hi'.length === 2 ? 'bg-salmon' : ''}`}> Hello world </div>

The curly braces we wrapped the template literal in mark the beginning of an expression that has to be evaluated.

The code between the opening an closing curly brace is just JavaScript, so any variable or expression we use in our template literals will get evaluated.

The second example in the code snippet uses the ternary operator.

<button className={`font-lg ${isActive ? 'bg-salmon text-white' : ''}`} onClick={handleClick} > Click </button>

The ternary operator is basically an if/else statement.

The part before the question mark gets evaluated and if it returns a truthy value, the operator returns the value before the colon, otherwise it returns the value after the colon.

In other words, if the isActive variable stores a true value, we add the bg-salmon and text-white classes to the element, otherwise we return an empty string.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.