Home > Blockchain >  React: How to add a button click handler to reveal text?
React: How to add a button click handler to reveal text?

Time:04-08

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?

CodePudding user response:

Use the useState hook.

const [reveal, setReveal] = useState(false);

const revealAnswer = () => {
    setReveal(reveal => !reveal)
}

...

return (
    ...
    {reveal && text}
    ...
)

CodePudding user response:

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!

  • Related