Handle onChange on input type=number

The default state is a number, adding and subtracting from the default state works as expected. When the input value is changed by typing a number in the input field the state changes to a string. What’s wrong here?

const [value, setValue] = useState(1);

 const handleChange = e => {
        setValue(e.target.value)
    }
    const handleAdd = () => {
        setValue(value+1)
    }
    const handleSubtract = () => {
        setValue(value-1)
    }
return (
<input type='number' value={value} onChange={handleChange} />
<button label='+' onClick={handleAdd} />
<button label='-' onClick={handleSubtract} />
)

Answer

Based on this:

The purpose of the number type is that mobile browsers use this for showing the right keyboards and some browsers use this for validation purposes.

To fix this, there is some approaches. But I suggest to you to parseInt the value when onChange. So:

  const [value, setValue] = useState(1);

  const handleChange = (e) => {
    setValue(parseInt(e.target.value));
  };
  const handleAdd = () => {
    setValue((prev) => prev + 1);
  };
  const handleSubtract = () => {
    setValue((prev) => prev - 1);
  };

  return (
    <div>
      <input type="number" value={value} onChange={handleChange} />
      <button label="+" onClick={handleAdd} />
      <button label="-" onClick={handleSubtract} />
    </div>
  );