Skip to content
react

How to hide and show elements in React

May 25, 2023Abhishek EH1 Min Read
How to hide and show elements in React

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"
2
3function App() {
4 const [isVisible, setIsVisible] = useState(true)
5
6 return (
7 <div>
8 <button>Toggle Visibility</button>
9 {isVisible && <div>This element is visible</div>}
10 </div>
11 )
12}
13
14export 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"
2
3function App() {
4 const [isVisible, setIsVisible] = useState(true)
5
6 const toggleVisibility = () => {
7 setIsVisible(!isVisible)
8 }
9
10 return (
11 <div>
12 <button onClick={toggleVisibility}>Toggle Visibility</button>
13 {isVisible && <div>This element is visible</div>}
14 </div>
15 )
16}
17
18export default App

Now if you click on the button, the visibility will be toggled.

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com