How to add multiple class names in React
In this tutorial, we are going to learn about how to conditionally add or remove multiple css class names to a react app.
Adding a single class name
We can add a single class name to the react element by using the className
attribute.
import React from 'react';
import './styles.css';
function App(){
return (
<div className="container"> <h1>Hello rock!!</h1>
</div>
)
}
export default App;
If you want to add multiple class names, you can add it to the className
attribute by separating with spaces.
import React from 'react';
import './styles.css';
function App(){
return (
<div className="container top-2 bottom-3"> <h1>Hello rock!!</h1>
</div>
)
}
export default App;
Adding multiple class names conditionally
We can add a multiple class names to the react element conditionally; by using template literals, ternary operator.
Conditionally means class names are only applied to the element when a particular condition is true, like if isActive
property is true we are adding a class name to the div
element, otherwise class name is removed.
Example:
import React, {useState} from 'react';
import './styles.css';
function App(){
const [isActive, setActive] = useState(false);
return (
<div className={`container top-3 ${isActive ? "shadow": ""}`}> <h1>Hello rock!!</h1>
<button onClick = {()=>setActive(!isActive)}> change classname
</button>
</div>
)
}
export default App;
In the above example, we are adding shadow
class name to a div
element, if isActive
property is true, otherwise we removed it.
Similarly, we can also add different class name to a div
element when an isActive
property is false.
<div className={`container top-3 ${isActive ? "shadow": "red-shadow"}`}>