Counter
Create a component that shows a number (starts from 0). Add two buttons to increment and decrement the counter.
Solution
0
Explanation
The code
It's clear that you'll need to keep track of the count with the useState
hook. Using the onClick
event listener enables you to move the count up or down. I have created two distinct functions, handleAdd
and handleMinus
to keep the code clean.
Top tip
To make sure your counter component doesn't run into any conflicts of state, you need to write your handlers using a functional update rather than updating state directly.
Code
import { useState } from "react";
import styles from "./Solution.module.css";
const Solution = () => {
const [count, setCount] = useState(0);
const handleAdd = () => {
setCount((prevCount) => prevCount + 1);
};
const handleMinus = () => {
setCount((prevCount) => prevCount - 1);
};
return (
<div className={styles.container}>
<p className={styles.counter}>{count}</p>
<div className={styles.buttons__container}>
<button className={styles.button} onClick={handleAdd}>
+
</button>
<button className={styles.button} onClick={handleMinus}>
-
</button>
</div>
</div>
);
};
export default Solution;
Styling
.container {
margin: 10px;
display: flex;
flex-direction: column;
gap: 10px;
border: 1px solid rgb(0, 0, 0);
border-radius: 5px;
width: 200px;
padding: 20px;
align-items: center;
}
.counter {
font-weight: bold;
}
.buttons__container {
display: flex;
gap: 10px;
}
.button {
display: grid;
place-content: center;
padding: 5px;
width: 30px;
aspect-ratio: 1 / 1;
line-height: 1;
}