I would like to keep the <input type="number" />. All the solutions I have seen want the input type to be text.
I have a form where users type a number (a dollar amount) and want the input to be for example 120,000 rather than 12000 as they are typing.
<input
  type="number"
  min="80000"
  max="2000000"
  step="1"
  value={borrowAmount}
  placeholder="value"
  onChange={e => setBorrowAmount(e.target.value)}
/>;
Have you tried react-number-format? It can add thousands separators nicely.
<NumberFormat 
  thousandSeparator={true} 
  prefix={'$'} 
  value={123456789}
  isAllowed={(values) => {
    const {floatValue} = values;
    return floatValue >= 5 &&  floatValue <= 10000;
  }}
/>
The onValueChange handler returns an object like this:
{
  "formattedValue": "$123,456,789",
  "value": "123456789",
  "floatValue": 123456789
}
Here is a simple approach:
const currencyFormatter = new Intl.NumberFormat(window.navigator.language, {
  style: 'currency',
  currency: 'USD',
  maximumFractionDigits: 2,
});
const FormattedInput = ({value, setValue, minValue, maxValue}) => {
  return (
    <input
      type="text"
      value={currencyFormatter.format(value)}
      onChange={(e) => {
        const nextValue = e.target.value.replace(/[^\d.]/g, '');
        setValue(Math.min(maxValue, Math.max(minValue, parseFloat(nextValue === '' ? '0' : nextValue))));  
      }}
    />
  )
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With