Counter
In this exercise, you’re tasked with creating a simple counter component that increments a number every time a button is clicked.
Expectations:
Every time the button is clicked, the number should increment by 1
Display the current number state in the text element
Solution Walkthrough for Counter
Spoiler Alert!
Don't read this unless you've already solved the problem.
onClick, which allows you to execute a function when an element is clicked. In this exercise, we'll use the onClick event handler to increment the counter when the button is clicked.count with 0:count using the useState hook and set its initial value to 0.const [count, setCount] = useState(0);handleIncrement function:handleIncrement that increments the count state variable by 1.function handleIncrement() {
setCount(count + 1);
}handleIncrement function to the button's onClick event handler:handleIncrement function to the onClick event handler of the button. This ensures that the function is called every time the button is clicked.<button onClick={handleIncrement}>Increment</button>Display the current count:
count state variable to display the current count in a paragraph element.<p>Count: {count}</p>