I’m using the slider in a react app and modifying the value
like so
<input
type="range"
className="frame-slider"
min="0"
value={currentValue.toString()}
onChange={(ev) => handleChange(parseInt(ev.target.value))}
max={maxLength}
/>
but when I run handleChange
(which is also being controlled by another number input) if I get a NaN then the slider jumps to the middle instead of 0 which is where the currentValue was.
Both inputs are being controlled by the same handleChange
but the input doesn’t get affected since it’s native for the user to erase the contents before typing something new I guess, but the slider keeps jumping instead of staying at its last position.
1
If the result of parseInt
is NaN
then you can account for that when setting the value, for example:
onChange={(ev) => handleChange(parseInt(ev.target.value) || 0)}
This would set the value to the resulting parsed integer, or to 0
if parsing failed.
Alternatively, you could allow it to set an empty value and check for that value in the display instead:
value={(currentValue || 0).toString()}
Another approach entirely could be to not switch between numbers and strings at all. It looks like the state value is a number, but at least in the code shown it always needs to be parsed from or converted to a string. So one option could be to always leave it as a string:
<input
type="range"
className="frame-slider"
min="0"
value={currentValue || 0}
onChange={(ev) => handleChange(ev.target.value)}
max={maxLength}
/>
The use of || 0
is still there to account for an empty string. But in this case the value is always a string so NaN
isn’t an issue. If other logic needs the value to be a number, it can be parsed when performing that logic instead.