0

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.

3
  • Use an object as your state instead of an int Commented Nov 11, 2020 at 7:15
  • Do you mean this? const [counter, setCounter] = useState({ count1: 0, count2: 0}) Commented Nov 11, 2020 at 7:19
  • yes. and then when you set the counter, reset the entire object: setCounter({count1: 2, ...counter}) Commented Nov 11, 2020 at 12:57

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.