| 1 |
import CurrencyInput from 'react-currency-input-field'; |
| 2 |
import {Controller, useFormContext} from 'react-hook-form'; |
| 3 |
|
| 4 |
type Props = { |
| 5 |
name: string; |
| 6 |
currency: string; |
| 7 |
placeholder?: string; |
| 8 |
disabled?: boolean; |
| 9 |
}; |
| 10 |
|
| 11 |
/** |
| 12 |
* @since 4.0.0 |
| 13 |
*/ |
| 14 |
function getNumberFormattingParts(): { groupSeparator: string; decimalSeparator: string } { |
| 15 |
const numberFormat = new Intl.NumberFormat(window.navigator.language); |
| 16 |
const parts = numberFormat.formatToParts(1234.56); |
| 17 |
|
| 18 |
let groupSeparator = ''; |
| 19 |
let decimalSeparator = ''; |
| 20 |
|
| 21 |
for (const part of parts) { |
| 22 |
if (part.type === 'group') { |
| 23 |
groupSeparator = part.value; |
| 24 |
} else if (part.type === 'decimal') { |
| 25 |
decimalSeparator = part.value; |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
return {groupSeparator, decimalSeparator}; |
| 30 |
} |
| 31 |
|
| 32 |
/** |
| 33 |
* @since 4.0.0 |
| 34 |
*/ |
| 35 |
export default ({name, currency, placeholder, disabled, ...rest}: Props) => { |
| 36 |
const {control} = useFormContext(); |
| 37 |
const {groupSeparator, decimalSeparator} = getNumberFormattingParts(); |
| 38 |
|
| 39 |
return ( |
| 40 |
<Controller |
| 41 |
name={name} |
| 42 |
control={control} |
| 43 |
render={({field}) => ( |
| 44 |
<CurrencyInput |
| 45 |
disabled={disabled} |
| 46 |
disableAbbreviations |
| 47 |
decimalSeparator={decimalSeparator} |
| 48 |
groupSeparator={ |
| 49 |
/** |
| 50 |
* Replace non-breaking space to avoid conflict with the suffix separator. |
| 51 |
* @link https://github.com/cchanxzy/react-currency-input-field/issues/266 |
| 52 |
*/ |
| 53 |
groupSeparator.replace(/\u00A0/g, ' ') |
| 54 |
} |
| 55 |
onValueChange={(value) => { |
| 56 |
field.onChange(Number(value ?? 0)); |
| 57 |
}} |
| 58 |
value={field.value} |
| 59 |
placeholder={placeholder} |
| 60 |
allowDecimals={true} |
| 61 |
allowNegativeValue={false} |
| 62 |
maxLength={9} |
| 63 |
intlConfig={{locale: window.navigator.language, currency}} |
| 64 |
{...rest} |
| 65 |
/> |
| 66 |
)} |
| 67 |
/> |
| 68 |
); |
| 69 |
}; |
| 70 |
|