logo
logo

Counter

Easy

Counter

Easy

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

Console
Submit
Solution
00:00

Solution Walkthrough for Counter

Key ReactJS Concepts:

Event Handling: React supports various event handlers, such as
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.

Solution Walkthrough:

Initialize state variable
count
with 0:
We create a state variable
count
using the
useState
hook and set its initial value to 0.
const [count, setCount] = useState(0);
Create the
handleIncrement
function:
We create a new function called
handleIncrement
that increments the
count
state variable by 1.
function handleIncrement() {
  setCount(count + 1);
}
Attach the
handleIncrement
function to the button's
onClick
event handler:
We connect the
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:

We use the
count
state variable to display the current count in a paragraph element.
<p>Count: {count}</p>