Hide and show in React JS functional component
In this tutorial, we will see how to hide or show a React JS
functional component. We will first create a button with label 'Show', when user clicks this button, a text message will be displayed and the button label will be changed to 'Hide'. When user again clicks on this button, it will hide the text message.
To achieve this behavior, we will use in build useState
React hook. useState
hook is used to maintain the state of a component among functional components without writing a class. We maintain the button state whether to show a show or hide button using 'buttonClicked' variable.
useState
returns the current state and a function that updates it.
Step 1) Create EditButton Component
EditButton component contains an button, if you click this button, 'Button clicked' text will be displayed on the page. useState(false) is initialized with buttonClicked as false.
const [buttonClicked, setButtonClicked] = useState(false);
'hideButton' & 'showButton' are event handlers for 'show' & 'hide' buttons when the button is clicked.
import React, { useState } from 'react'const EditButton = (props) => { const [buttonClicked, setButtonClicked] = useState(false); const hideButton = () => { setButtonClicked(true); } const showButton = () => { setButtonClicked(false); } return <div className='new-expense'> {!buttonClicked && <button type='submit' onClick={hideButton}>Show</button>} {buttonClicked && <div><p>Button clicked/p> <button type='submit' onClick={showButton}>Hide</button></div>} </div>}export default EditButton;
Step 2) Create App.js
import EditButton from './EditButton';import './App.css';function App() { return ( <EditButton /> );}export default App;
If you run npm start
, you will see 'Show' button on broswer, when you click it, 'Button clicked' text message will be displayed on screen & button label will change to 'Hide'.