increment, decrement multiple elements of an elements in reactjs

So I have 10 divs rendered through map function but I want to increment/decrement the respective element value and display on a element Code :
let arr= ["item1","item2","item3"...,"item10"]
const [quantity, setQuantity]=useState(0)

function Increment (){
setQuantity (quantity+1)
}

function Decrement (){
setQuantity (quantity-1)
}

{
arr.map((key,val)=>{
return <div key={key}
<p> {val} </p>
<button onClick={Increament}> Increment </button>
<p> {quantity} </p>
<buttononClick={Decreament}> Decrement </button>

</div>
}
)}
let arr= ["item1","item2","item3"...,"item10"]
const [quantity, setQuantity]=useState(0)

function Increment (){
setQuantity (quantity+1)
}

function Decrement (){
setQuantity (quantity-1)
}

{
arr.map((key,val)=>{
return <div key={key}
<p> {val} </p>
<button onClick={Increament}> Increment </button>
<p> {quantity} </p>
<buttononClick={Decreament}> Decrement </button>

</div>
}
)}
2 Replies
Chooβ™šπ•‚π•šπ•Ÿπ•˜
I'm not sure how that could have any real world use. It's unclear if you want all elements to have the same value or if all elements can have different values but must increment and decrement by the same amount. If they all must have the same value, just put {quantity} in all of them. If each item can have a different value, your code is not structured correctly to handle this. The arr only holds strings and the quantity state only holds a single number. The state should actually be an array of objects that have both the string and number as properties. To increment or decrement, the click handler would then use a map to alter all the quantity values.
clevermissfox
clevermissfoxβ€’3mo ago
btw your onClick={Increment} is misspelled as is <buttononClick={Decreament}
Want results from more Discord servers?
Add your server