Today's task is to create the famous counter app, with the following instructions:
- The counter should start from 0
- Click the "+" button to increment
- Click the "-" button to decrement
The boilerplate code for this:
import React from 'react'
export function App() {
return (
<div>
<button data-testid="decrement-button">-</button>
<button data-testid="increment-button">+</button>
<p>clicked: 0</p>
</div>
)
}
First, declare the variables to change the state of the value to be increased and decreased.
const[count, setCount] = useState(0);
Then create the functions to increase and decrease the count
const handleIncrease = () => {
setCount(count + 1);
}
const handleDecrease = () => {
setCount(count - 1);
}
Finally, add the functions to the respective buttons, then update the state
<button onClick={handleDecrease} data-testid="decrement-button">-</button>
<button onClick={handleIncrease} data-testid="increment-button">+</button>
<p>clicked: {count}</p>
The final output looks like this:
import React, {useState} from 'react'
export function App() {
const [count, setCount] = useState(0);
const handleIncrease = () => {
setCount(count + 1);
}
const handleDecrease = () => {
setCount(count - 1);
}
return (
<div>
<button onClick={handleDecrease} data-testid="decrement-button">-</button>
<button onClick={handleIncrease} data-testid="increment-button">+</button>
<p>clicked: {count}</p>
</div>
)
}
That's all folks!
Top comments (0)