How to Add Multiple Classes in React

Updated onbyAlan Morel
How to Add Multiple Classes in React

React is a popular UI library that lets you build web applications using components.

One of the most important ways to style your components is by using CSS classes.

In this post, we will look at how to add multiple CSS classes in React.

How to add a single class in React

Before we see examples of multiple classes, let's first look at how to add a single class in React.

Remember that in React, you can add a class to an element by using the className attribute, not the class attribute.

That looks like this:

JSX
const App = () => { return ( <div> <h1 className="header">Hello World</h1> </div> ); }

This applies the class header to the h1 element.

How to add multiple classes in React

Now, let's look at how to add multiple classes in React.

The most straightforward way to add multiple classes is to just add more classes by separating them with a space.

Here's an example:

JSX
const App = () => { return ( <div> <h1 className="header large">Hello World</h1> </div> ); }

Now the h1 element has two classes: header and large.

How to add multiple classes conditionally in React

Sometimes, you may want to add multiple classes conditionally.

For example, you may want to add a class if a certain condition is true.

To do this, simply add a class based on the condition.

Here's an example:

JSX
const App = () => { const isLarge = true; return ( <div> <h1 className={`header ${isLarge ? 'large' : ''}`}>Hello World</h1> </div> ); }

In this case, the class large will only be added if the variable isLarge is true.

This is a powerful technique that allows you to have full control over which classes are added to your elements.

Conclusion

In this post, we saw how to add a single class, how to add multiple classes, and then how to add them conditionally.

Simply use the className attribute to add classes to your elements, and separate multiple classes with a space.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.