I have an input field that takes numbers and i want to change the value by keyboard input but also via buttons.
The buttons work fine as long as I don´t use keyboard input.
If I type in 10 for example and add 1 with the button the value changes to 101 and not to 11 as I expected. On the other hand, when I decrement the value with the button it works correctly again.
How can I make it work correctly?
I would be grateful for your help…
const [maxAmount, setMaxAmount] = useState(0);
const decrementMaxAmount = () => {
if (maxAmount > 0) setMaxAmount(maxAmount - 1);
};
const incrementMaxAmount = () => {
setMaxAmount(maxAmount + 1);
};
<button onClick={() => decrementMaxAmount()}>
<button onClick={() => incrementMaxAmount()}>
<input
type="number"
name="maxAmount"
value={maxAmount}
onChange={(event) => setMaxAmount(event.target.value)}
/>
>Solution :
Type of event.target.value is a string. So your maxAmount is a string :
maxAmount + 1 === "10" + 1 === "101".
To avoid this, you can convert your type with the Number() constructor :
setMaxAmount(Number(event.target.value))