Table of Contents
In this article, we will see how to use the React useState hook and how to show and hide an element when a button is clicked.
Project setup
Create a react app using the following command
1npx create-react-app react-hide-show-element
Adding the button and initializing the state
Update App.js with the following code:
App.js
1import React, { useState } from "react"23function App() {4 const [isVisible, setIsVisible] = useState(true)56 return (7 <div>8 <button>Toggle Visibility</button>9 {isVisible && <div>This element is visible</div>}10 </div>11 )12}1314export default App
Here, we have a button and a div element. The div element will be visible when the isVisible state is true.
Adding the onClick handler and hiding the element
We can add a click handler to the button and toggle the isVisible state.
App.js
1import React, { useState } from "react"23function App() {4 const [isVisible, setIsVisible] = useState(true)56 const toggleVisibility = () => {7 setIsVisible(!isVisible)8 }910 return (11 <div>12 <button onClick={toggleVisibility}>Toggle Visibility</button>13 {isVisible && <div>This element is visible</div>}14 </div>15 )16}1718export default App
Now if you click on the button, the visibility will be toggled.
If you have liked article, do follow me on twitter to get more real time updates!