Table of Contents
React makes it super easy to build a data-driven UI.
One of the most common patterns is to toggle a class on an element based on some state. For example, you might want to show a dropdown menu when a user clicks a button.
In this post, we'll learn how to toggle a class on an element in React.
How to toggle a class in React
Let's start with a simple example. We'll create a button that toggles a class on a div when it's clicked.
JSXimport React, { useState } from "react";
const App = () => {
const [show, setShow] = useState(false);
return (
<div>
<button onClick={() => setShow(!show)}>Toggle</button>
<div className={show ? "show" : ""}>Hello</div>
</div>
);
}
export default App;
Here, we use the useState
hook to create a boolean state variable called show
. We then use the onClick
event to toggle the state variable.
Finally, we use the ternary operator to toggle the class on the div
.
Now, if you want to toggle between two different classes, that is simple.
JSXimport React, { useState } from "react";
const App = () => {
const [show, setShow] = useState(false);
return (
<div>
<button onClick={() => setShow(!show)}>Toggle</button>
<div className={show ? "show" : "hide"}>Hello</div>
</div>
);
}
export default App;
Here, instead of toggling between an empty string and a class name, we toggle between two different class names.
Conclusion
In this article, we learned how to toggle a class on an element in React.
Simply create a boolean using useState
and toggle it using the onClick
event. Then, use the ternary operator to toggle the class on the element you want.
Thanks for reading!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Getting Started with Svelte
- Create an RSS Reader in Node
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js