I have a react component similar to this:
export default function App() {
const [minVal, setMinVal] = useState(-19.0);
const [maxVal, setMaxVal] = useState(17.65);
const steps = 0.25;
const [val, setVal] = useState(0);
useEffect(() => {
setMinVal(Number(minVal).toFixed(2));
setMaxVal(Number(maxVal).toFixed(2));
let avg = ((Number(minVal) + Number(maxVal)) / 2).toFixed(2);
avg = Number(avg);
setVal(avg);
}, [minVal, maxVal]);
const onMinValChange = (e) => {
setMinVal(Number(e.target.value).toFixed(2));
};
const onMaxValChange = (e) => {
setMaxVal(Number(e.target.value).toFixed(2));
};
return (
<div className="App">
<p> The min value is {minVal} </p>
<p> The max value is {maxVal} </p>
<p> The value is {val} </p>
<label for="min">
Min Value:
<input
type="number"
min={minVal}
max={maxVal}
step={steps}
value={minVal}
id="min"
onChange={onMinValChange}
/>
</label>
<label for="max">
Max Value:
<input
type="number"
min={minVal}
max={maxVal}
step={steps}
value={maxVal}
id="max"
onChange={onMaxValChange}
/>
</label>
</div>
)}
here I am unable to enter any desired value after the decimal using my keyboard. Please note that I can’t change the ‘step’ value here. I also need to display the value upto 2 decimal places.
You can check this codesandbox as well to see how it is working currently.
2
Answers
Every time you try to enter something in the decimal point, your
onMinValChange
andmax
functions will forcefully update the value to 2 decimal points, consequently making it impossible to update the decimal point after the second position UNLESS you select one of the decimal points, and directly replace that digit instead of inserting a new digit.Therefore, the fix will be to remove all the
.toFixed(2)
for the setStates, but only add that in the UI.Specifically, change
setMinVal(Number(minVal).toFixed(2));
to justsetMinVal(Number(minVal));
, and update your UI withLike I have seen you are updating 2 decimal points(toFixed(2)) when user change input box, instead of you can do update when user leave that input for that you can find onBlur event in react input box, I have update demo in below link you can follow the same
https://codesandbox.io/s/intelligent-noyce-vcc596?file=/src/App.js
Let me know if you have any doubt or further query