import { forwardRef, useEffect, useMemo } from 'react'; import { TextInput, TextInputProps } from 'react-native'; import currencyFormatter from 'currency-formatter'; import { CurrencyInputProps } from './types'; export const CurrencyInput = forwardRef(({ renderTextInput, value, onChangeText, onChangeValue, currency, locale, symbol, decimal, thousand, precision, format, ...rest }, ref) => { const formattedValue = useMemo(() => { if (!(!!value || value === 0 || value === -0)) { return ''; } return currencyFormatter.format(value, { code: currency, locale, symbol, decimal, thousand, precision, format, }) }, [ value, currency, locale, symbol, decimal, thousand, precision, format, ]); useEffect(() => onChangeText?.(formattedValue), [formattedValue]); const handleChangeText = (text: string) => { const number = currencyFormatter.unformat(text, { code: currency, locale, symbol, decimal, thousand, precision, format, }); onChangeValue?.(number); }; const nextProps: TextInputProps = useMemo(() => ({ keyboardType: 'numeric', value: formattedValue, onChangeText: handleChangeText, ref: ref, }), [formattedValue]); if (renderTextInput) { return renderTextInput(nextProps); } return ; });