DEV Community

Discussion on: How to show or hide element in React

Collapse
 
wannabehexagon profile image
ItsThatHexagonGuy • Edited

You've only written the logic to show the text, not hide it. Also, avoid naming your handlers the same as the event. Change your handler code to:

const handleClick = () => setToggleText((isTextShown) => !isTextShown);
Enter fullscreen mode Exit fullscreen mode

Now, whenever the user clicks on the button, the text will either be hidden if it's already showing up or show up if it's hidden.

PS: I've used a function instead of a value for the setToggleText() function because showing/hiding the text depends on the most up to date value of isTextShown.

Collapse
 
mohammedasker profile image
Mohammed Asker

Oh, wow, thanks for taking the time to suggest a better solution! Indeed, the current code does only hiding the elements and not showing because this approach solved my problem. Your code is much better and works for any solution.

I'm going to update the post soon.