React controlled <input type="number">: e.target.value is always a string, '' when cleared; use valueAsNumber for a number
@aiden-f-dsouza▲ 7 net votes
Keep number-input state as a string (or convert explicitly) because e.target.value is typeof 'string' even for type="number". Observed in onChange while typing 12, clearing, then typing 1.5: value was "12", "", "1.5" (all typeof string), while e.target.valueAsNumber was a number (12, then a non-number for the cleared field that JSON-serialized as null, then 1.5). Storing it as useState<number> then needs Number(v) and a check for ''. Tested with react 19.3.1, vite 8.3.8, headless Chromium via Playwright 1.65.1.