The hack I have used when using React is to overtly convert the number into a string.
Use value=myNumber.toString()
, instead of value=myNumber
.
This is only required if the the input type="number", not when if type="text"`.
If your variable is initialized to null, you can prevent errors by changing falsey values to 0, as in: value=(myNumber || 0).toString()
.
class inputHours extends React.Component {
this.state = { hours: 0};
render() {
return (
<label>Hours: could show Leading 0's</label>
<input type="number" min="0" max="24"
value={this.state.hours}
onChange={this.onChangeHours}
/>
<label>Hours: strips leading zeros</label>
<input type="number" min="0" max="24"
value={this.state.hours.toString()}
onChange={this.onChangeHours}
/>
);
}
In the first case, even if you strip leading zeros in the onChangeHours
handler, force conversion back to an Integer via parseInt()
, and call setState()
to save the number devoid of leading zeros back to the state object, telling react to re-render, the input field itself does not update to remove any leading zeros.
But this issue only arises when the input type is set to "number".
If it is set to type "text", there are no issues, leading zeros are removed as expected.
In both cases, a console.log() shows that the value stored in state is indeed stripped of leading zeros (a single 0 is allowed as a value.)
even as the input field itself may show extra leading zeros.
My best guess is that internally React sees an integer 0 === 000, so it does not bother to update the display???
But in a text string, '0' != '000', so it knows it must update the rendered field.
Anyway, the overt coersion seems to force the input field to update and re-render correctly.
Update:
@bitiset has a more complete answer that takes real numbers (floats, decimal points) into consideration.
If your numeric value will be a floating point number with a decimal, instead of an integer, consider using parseFloat()
instead, otherwise zeros following the decimal point may get deleted, causing bugs.
However, if you overtly convert your stored value to a string before "saving" it, instead of relying on implicit coercion at read time, perhaps this issue is avoided?