I want to create an input React component for a monetary amount and I would like the placeholder to be 0.00 but upon typing, the value should be updated digit by digit without the need to type a .
. So, for example, an amount of 1,234.56 should show as:
0.01
0.12
1.23
12.34
123.45
1,234.56
And when erasing a number then the revert order:
1,234.56
123.45
12.34
1.23
0.12
0.01
But, unfortunately, I can’t get any of it to work. I tried an onChange
event and onKeyDown
event too with no success.
I am using a ShadCN component if that matters
2
Answers
You can listen to a change event, get the value from the input field and then format it as you want :
You could format the currency with a number formatter, and parse it with
parseInt
.You will need to format on
input
, and validate onkeydown
.