'React: How to add a button click handler to reveal text?
I want create a button click handler to reveal the answer text "Animal". So far I have <button onClick={this.revealAnswer}>Reveal answer</button> and the handler
revealAnswer = () => { };
What information should I put in the handler?
Solution 1:[1]
Use the useState hook.
const [reveal, setReveal] = useState(false);
const revealAnswer = () => {
setReveal(reveal => !reveal)
}
...
return (
...
{reveal && text}
...
)
Solution 2:[2]
You can add a state variable (boolean type) to the component, something like const [revealAnswer, setRevealAnswer] = useState(false). Here, 'false' being the default value.
In the handler, you can then update the state every time the button gets clicked.
const revealAnswer = () => {
setRevealAnswer(!revealAnswer);
};
And in your JSX you should have condition based on this variable revealAnswer. Eg:
...
{ revealAnswer && textValue }
Hope that helps!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | neilge |
| Solution 2 | Manul Aggarwal |
