|
| 1 | +import React, { useState } from 'react'; |
| 2 | +import { InputProps } from '../Input/Input'; |
| 3 | +import { StyledCurrency } from './CurrencyStyles'; |
| 4 | + |
| 5 | +export type CurrencyInputProps = Omit< |
| 6 | + InputProps, |
| 7 | + 'type' | 'prefix' | 'onChange' | 'value' |
| 8 | +> & { |
| 9 | + locale?: string; |
| 10 | + value?: number; |
| 11 | + onChange?: (value: number) => void; |
| 12 | +}; |
| 13 | + |
| 14 | +export const CurrencyInput = ({ |
| 15 | + locale = 'en', |
| 16 | + value = 0, |
| 17 | + onChange, |
| 18 | + ...props |
| 19 | +}: CurrencyInputProps) => { |
| 20 | + // eslint-disable-next-line @typescript-eslint/ban-ts-comment |
| 21 | + // @ts-ignore |
| 22 | + const supportedLocale = Intl.ListFormat.supportedLocalesOf(locale); |
| 23 | + const localeValue = supportedLocale.length > 0 ? supportedLocale[0] : 'en'; |
| 24 | + |
| 25 | + if (supportedLocale.length === 0) { |
| 26 | + console.warn(`Locale value of ${locale} is unsupported, "en" will be used`); |
| 27 | + } |
| 28 | + |
| 29 | + const formatter = new Intl.NumberFormat(localeValue); |
| 30 | + |
| 31 | + const getRawNumber = (value: string) => { |
| 32 | + if (typeof value === 'number') { |
| 33 | + return value; |
| 34 | + } |
| 35 | + |
| 36 | + const parts = formatter.formatToParts(1000.1); |
| 37 | + const thousandSeparator = parts[1].value; |
| 38 | + const decimalSeparator = parts[3].value; |
| 39 | + |
| 40 | + const cleanedValue = parseFloat( |
| 41 | + value |
| 42 | + .replace(new RegExp('\\' + thousandSeparator, 'g'), '') |
| 43 | + .replace(new RegExp('\\' + decimalSeparator), '.') |
| 44 | + ); |
| 45 | + |
| 46 | + return Number.isNaN(cleanedValue) ? 0 : cleanedValue; |
| 47 | + }; |
| 48 | + |
| 49 | + const [formattedValue, setFormattedValue] = useState( |
| 50 | + formatter.format(getRawNumber(value.toString())) |
| 51 | + ); |
| 52 | + |
| 53 | + const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { |
| 54 | + const rawValue = getRawNumber(e.currentTarget.value); |
| 55 | + onChange(rawValue); |
| 56 | + setFormattedValue(formatter.format(rawValue)); |
| 57 | + }; |
| 58 | + |
| 59 | + return ( |
| 60 | + <StyledCurrency |
| 61 | + type="text" |
| 62 | + prefix={<div>$</div>} |
| 63 | + {...props} |
| 64 | + value={formattedValue === '0' ? '' : formattedValue} |
| 65 | + onChange={handleChange} |
| 66 | + /> |
| 67 | + ); |
| 68 | +}; |
0 commit comments