'How to increase and decrease values on button clicking?
I am trying to implement an increase and decrease on button click. But I cannot figure out how to do that. I have tried to declare to increase and decrease its value by using a button, but that didn't work. Anyone help...
Solution 1:[1]
How to increase and decrease values on button click ?
Code:
import { useState } from "react";
import "./styles.css";
export default function App() {
const [counter, setCounter] = useState(0)
const handleAdd=()=>{
setCounter(counter+1)
}
const handleSub=()=>{
setCounter(counter-1)
}
return (
<div className="App">
<button onClick={handleAdd}>Add 1</button>
<button onClick={handleSub}>Subtract 1</button>
<h1>{counter}</h1>
</div>
);
}
Here's a Sandbox for you to try: https://codesandbox.io/s/cold-fire-oeozl2?file=/src/App.js
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alon Barenboim |
