I want to save the input in number type every time the value updates. However, with this approach, The value is stuck in NaN or 0 in the scenarios below.
scenario 1: changing 0 to 0.1 (stuck in 0 when '0.' left)
scenario 2: changing -15 to 1 (stuck in NaN when only '-' left)
What would be the best way to handle these cases when 1) the input has to be controlled element and 2) storing value in string format is not an option?
export default function App() {
const [input, setInput] = useState(0)
return (
<div className="App">
<input value={input} onChange={(e)=>setInput(parseFloat(e.target.value))}/>
</div>
);
}
You can add a check before setting the state to see if the input value is parsable to a float.
function checkSetInput(e) {
const val = parseFloat(e.target.value);
if (isNaN(val))
return // do not set state when the input is not parsable
setInput(val); // otherwise do set the state
}
...
<input value={input} onChange={checkSetInput} />