Sometimes, we want to set the class
attribute conditionally within our React component.
In this article, we’ll look at how to set the class
attribute conditionally within our React component.
Conditionally Apply Class Attribute Values with React
We can set the className
prop conditionally to set the class
attribute of an element conditionally.
For instance, we can write:
import React, { useState } from "react";
export default function App() {
const [show, setShow] = useState(false);
return (
<>
<style>
{`
.is-shown {
display: block
}
.is-hidden {
display: none
}
`}
</style>
<button onClick={() => setShow((s) => !s)}>toggle</button>
<div className={show ? "is-shown" : "is-hidden"}>hello</div>
</>
);
}
We have the styles for the is-shown
and is-hidden
class in the style
element.
Then we have a button that calls setShow
to toggle the show
state between true
and false
.
And then we set className
to 'is-shown'
is show
is true
and 'is-hidden'
otherwise.
Now when we click on the button, we see the div being shown or hidden because we applied the class according to the value of show
.
Conclusion
We can set the className
prop conditionally to set the class
attribute of an element conditionally.