I would like a text to be displayed on the screen and only be hidden when pressing a button, but I don't know how. I thought of using useState like this:
const [textVisibility, setTextVisibility] = useState(true)
<button onClick={() => setTextVisibility(false)} />
the problem I found is that when clicking on the button the page will be rendered again and the visibility value will be the default value (true). How can I do that?
CodePudding user response:
Idk what are you experiencing but for me it works fine the following code:
import React from 'react';
import {useState} from 'react';
export function App(props) {
const [textVisibility, setTextVisibility] = useState(true)
return (
<div className='App'>
{textVisibility && <h1 onClick={() => setTextVisibility(!textVisibility)}>Hello React.</h1>}
<button onClick={() => setTextVisibility(false)}>Invisible</button>
<button onClick={() => setTextVisibility(true)}>Visible</button>
</div>
);
}
CodePudding user response:
const App(){
const [isVisible, setIsVisible] = useState(false)
return (
<>
{isVisible ? <label> This text will be shown on button click </label> : null
}
<button onClick={()=>setIsVisible(true)}>click to show </button>
</>
)
}