Reputation: 3
I would like to create an input field that formats the value as follows
> The default value is 0.00
> 0.00, I press 2 and get 2.00
> 0.|00, I press 2 and get 0.20
> 0.0|0, I press 2 and get 0.02
So far, all of this works as expected, but when the user places the cursor like this 0|.00, presses 2. In that case, nothing happens I would like for it to become 2.00 but I can't achieve that because I needed to disallow leading zeros which I've done using the isAllowed
prop. If I remove it, the zeros I type are gone after the input loses focus but I don't want to be able to write any leading zeros.
Any help is appreciated.
I use react-number-format and this is the current code I have
const [value, setValue] = useState(0);
return (
<NumericFormat
value={value}
decimalScale={2}
decimalSeparator=","
thousandSeparator="."
suffix=" EUR"
fixedDecimalScale
isAllowed={(values) => {
const {value, floatValue} = values;
if (value.charAt(0) === '0') {
if (value.charAt(1) && value.charAt(1) !== '.') {
return false;
}
}
return true;
}}
allowNegative={false}
onValueChange={(values) => {
const {formattedValue, value, floatValue} = values;
console.log(values);
if (value.charAt(0) !== '0' && value.charAt(1) === '0') {
console.log('split[0]', value.split('')[0]);
return setValue(+value.split('')[0]);
}
if (value.charAt(0) === '0' && value.charAt(1) !== '0') {
console.log('split[1]', value.split('')[1]);
const valueToSet = +value.split('')[1];
return setValue(!Number.isNaN(valueToSet) ? valueToSet : 0);
}
if (value === '') {
return setValue(0);
}
return setValue(floatValue!);
}}
/>
Upvotes: 0
Views: 189