Toggle Visibility
In this exercise, you're tasked with creating a component that toggles the visibility of a piece of text when a button is clicked. Expectations:
Initially, the text should be hidden
When the button is clicked, the text should become visible if it was hidden, and hidden if it was visible
useState
hook to manage the visibility stateSolution Walkthrough for Toggle Visibility
Spoiler Alert!
Don't read this unless you've already solved the problem.
Conditional Rendering:
React allows you to conditionally render elements based on a certain condition. In this exercise, we'll use conditional rendering to display or hide the text element based on the visibility state.
Event Handling:
onClick
, which allows you to execute a function when an element is clicked. In this exercise, we'll use the onClick
event handler to toggle the visibility state when the button is clicked.isVisible
with false
:isVisible
using the useState
hook and set its initial value to false
, indicating that the text should be initially hidden.const [isVisible, setIsVisible] = useState(false);
handleToggleVisibility
function:handleToggleVisibility
that toggles the isVisible
state variable by setting it to its opposite value (!isVisible
).function handleToggleVisibility() {
setIsVisible(!isVisible);
}
handleToggleVisibility
function to the button's onClick
event handler:handleToggleVisibility
function to the onClick
event handler of the button. This ensures that the function is called every time the button is clicked, toggling the visibility of the text element.<button onClick={handleToggleVisibility}>Show/Hide Text</button>
isVisible
state:isVisible
state is true
.{isVisible && <p>Toggle me!</p>}