ArthurPedroti / comments

0 stars 0 forks source link

currency-input-or-any-input-with-mask-integration-with-react-hook-form-and-zod/ #6

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

Currency Input (or any Input with Mask) integration with React Hook Form and Zod | Arthur Pedroti

How to properly integrate these libraries and their limitations

https://arthurpedroti.com.br/currency-input-or-any-input-with-mask-integration-with-react-hook-form-and-zod/

felipe-miranda-marreiros commented 1 year ago

For those who using Chakra UI.


function currencyBRLFormatter(value: string) {
  if (!Number(value)) return ''

  const number = Number(value)

  const amount = new Intl.NumberFormat('pt-BR', {
    style: 'currency',
    currency: 'BRL'
  }).format(number / 100)

  return `${amount}`
}

export const CurrencyInputField = <TValues extends FieldValues>({
  name,
  control,
  label
}: UseControllerProps<TValues> & { label: string }) => {
  return (
    <Controller
      name={name}
      control={control}
      render={({ field: { ref, ...fieldProps }, fieldState }) => {
        return (
          <FormControl isInvalid={fieldState.invalid}>
            <FormLabel>{label}</FormLabel>
            <NumberFormatBase
              getInputRef={ref}
              placeholder="R$"
              format={currencyBRLFormatter}
              {...fieldProps}
            />
            <FormErrorMessage color="red">{fieldState.error?.message}</FormErrorMessage>
          </FormControl>
        )
      }}
    />
  )
}