Reputation: 107
I had this problem several counts to be increment upon click.
let count = [{id: 1, value 0}, {id: 2, value 0}]
const [counter,setCounter] = useState(counter)
increment = () => {
I want to set counter value depends on the button click and the counter will add 1 only to the specific count above.
}
return <div>
<input type='text' value='count1'>{count1}</h2> <- I know that this does not work
<button onClick={increment()}>+</button>
<input type='text' value='count1'>{count2}</h2>
<button onClick={increment()}>+</button>
Thanks.
Upvotes: 0
Views: 1093
Reputation: 594
Not sure what you're exactly trying to do, but I think this should help you out
import React, { useState } from "react";
import "./styles.css";
export default function App() {
let count = {
1: 0,
2: 0
};
const [counter, setCounter] = useState(count);
const increment = (id) => {
setCounter({ ...counter, [id]: counter[id] + 1 })
};
return (
<div className="App">
<input type='text' id="1" value={counter[1]}></input>
<button onClick={() => { increment(1) }}>+</button>
<input type='text' id="2" value={counter[2]}></input>
<button onClick={() => { increment(2) }}>+</button>
</div>
);
}
You can run the codesandbox here https://codesandbox.io/s/dank-mountain-bmkgi
Upvotes: 1