'Multiple Increments for multiple inputs
Code should increment or decrement his own input, for diameter should work only button for diameter etc. But every click increment all inputs
The problem is every click increment all inputs that i want to change
const [countDiameter,setCountDiameter] = useState(1);
const [countFriction,setCountFriction] = useState(1);
const [countRobotsQnt, setCountRobotsQnt] = useState(1);
const [countSimulationTime, setCountSimulationTime] = useState(1);
const incrementCount = () =>{
setCount(countDiameter + 1);
};
const decrementCount = (i) =>{
if(countDiameter>0){setCount(countDiameter -1);}
};
<div className='inputForm'>
<input type="number" id='InputDiameter' pattern="^-?[0-9]\d*\.?\d*$" value = {count} onChange={(event) =>{ setCount(event.target.value) }}/>
<label for="InputDiameter" className='static-value'>w</label>
</div>
<div className='ButtonCount' onClick={incrementCount}><button type='button'><span className="countText">+</span></button></div>
<div className='ButtonCount' onClick={decrementCount}><button type='button'><span className="countText">-</span></button></div>
</div>
<div className='inputForm'>
<input type="number" id='InputNumber' pattern="^-?[0-9]\d*\.?\d*$" value = {count} onChange={(event) =>{ setCount(event.target.value) }}/>
<label for="inputNumber" className='static-value'>qnt</label>
</div>
<div className='ButtonCount' onClick={incrementCount}><button type='button'><span className="countText">+</span></button></div>
<div className='ButtonCount' onClick={decrementCount}><button type='button'><span className="countText">-</span></button></div>
</div>
Solution 1:[1]
I am not that familiar with React, but according to the comments above, I would have tried the following:
First, set a generic decrement and increment function that accepts a state and a setter function.
const incrementState = (setter, state)=>{
setter(state + 1)
}
const decrementState = (setter, state)=>{
if (state > 0) {
setter(state - 1);
}
}
[diameter, setDiameter] = setState(1/*or your desired initial value*/)
In your HTML code, you can then call your decrement/increment function by passing the above parameters to this function:
<div className='inputForm'>
<input type="number" id='InputDiameter' pattern="^-?[0-9]\d*\.?\d*$" value={diameter} onChange={(event)=>{
setDiameter(event.target.value) }}/>
<label for="InputDiameter" className='static-value'>w</label>
</div>
<div className='ButtonCount' onClick={incrementState(setDiameter,diameter)}><button type='button'><span
className="countText">+</span></button></div>
<div className='ButtonCount' onClick={decrementState(setDiameter,diameter)}><button type='button'><span
className="countText">-</span></button></div>
</div>
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 | Empiire |
