Maybe without DOM manipulation can solve this problem lot easier:
import React, { useState } from 'react'; const changeHandler = setter => ({target:{value}}) => setter(value); export default () => { const [counter, setCounter] = useState(0); return ( <pre> <input value = {counter} onChange={changeHandler(setCounter)}/> <button onClick={ _ => setCounter(v => +v ? +v + 1 : 1)}> + </button> <button onClick={ _ => setCounter(v => +v ? +v - 1 : -1)}> - </button> </pre> ); }
when need lot of counters we can give value / set function (action) to each one:
import React, { useState } from 'react'; const changeHandler = setter => ({target:{value}}) => setter(_ => value); const InputCounter = ({counter, setCounter}) => ( <div> <input value = {counter} onChange={changeHandler(setCounter)}/> <button onClick={ _ => setCounter(v => +v ? +v + 1 : 1)}> + </button> <button onClick={ _ => setCounter(v => +v ? +v - 1 : -1)}> - </button> </div> ); export default () => { const [counterList, setCounterList] = useState([1,2,3,4,'wrong starting value',7,'1e10','0xfdf']); const setIndexed = index => setter => setCounterList( list => list.map( (v, i) => i === index ? setter(v) : v ) ); return ( <pre> {counterList.map( (counter, index) => ( <InputCounter counter={counter} key={index} setCounter={setIndexed(index)} /> ) )} {JSON.stringify(counterList ,null , 2)} </pre> ) }
bonus: works with hexadecimal values written 0xABC format
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Maybe without DOM manipulation can solve this problem lot easier:
when need lot of counters we can give value / set function (action) to each one:
bonus: works with hexadecimal values written 0xABC format