Skip to content

React Hook Form integration

Use NumoraInput with React Hook Form through its Controller component.

numora-react does not depend on react-hook-form. Install it in your project yourself.

Controller pattern

Spread field onto NumoraInput. It forwards name, value, onChange, onBlur, ref and disabled.

In onChange, React Hook Form reads e.target.value. On NumoraInput that is the raw value, so the form stores "1234.5" in every locale. onBlur tracks the touched state. ref focuses the field on a validation error.

Give the field a string in defaultValues, so it is controlled from the first render.

A form with one Controller field. setValue() updates the input. The live field shows the input alone, without the form.

import { useForm, Controller } from 'react-hook-form'
import { NumoraInput } from 'numora-react'

function Form() {
  const { control, handleSubmit, setValue } = useForm({
    defaultValues: { amount: '' },
  })

  return (
    <form onSubmit={handleSubmit((data) => console.log(data))}>
      <Controller
        control={control}
        name="amount"
        render={({ field }) => <NumoraInput {...field} decimalMaxLength={2} />}
      />
      <button type="button" onClick={() => setValue('amount', '1000')}>
        Set to 1000
      </button>
      <button type="submit">Submit</button>
    </form>
  )
}

Validation errors

Show the message from fieldState.error. Validate with a validate function that works on the string. React Hook Form's min and max rules convert the value to a JavaScript number, which loses precision on long amounts.

<Controller
  control={control}
  name="amount"
  rules={{
    required: 'Amount is required',
    // The form value is a string. Compare it as text or with a decimal library;
    // `min` would convert it to a float.
    validate: (value) => /^[1-9]/.test(value) || 'Must be at least 1',
  }}
  render={({ field, fieldState: { error } }) => (
    <>
      <NumoraInput {...field} decimalMaxLength={2} />
      {error && <span>{error.message}</span>}
    </>
  )}
/>

The same goes for a schema resolver. Keep the amount a string in the schema, such as Zod's z.string(). z.coerce.number() converts it to a JavaScript number.

Reusable field

To use the field in several forms, wrap it once with useController. The wrapper gives name, control, rules and disabled to React Hook Form, and passes every other prop to NumoraInput. Set the initial value in the form's defaultValues.

import { useController, type FieldValues, type UseControllerProps } from 'react-hook-form'
import { NumoraInput, type NumoraInputProps } from 'numora-react'

type AmountFieldProps<T extends FieldValues> = Pick<
  UseControllerProps<T>,
  'name' | 'control' | 'rules' | 'disabled'
> &
  Omit<NumoraInputProps, 'name' | 'disabled' | 'value' | 'defaultValue' | 'onChange' | 'onBlur'>

function AmountField<T extends FieldValues>({
  name,
  control,
  rules,
  disabled,
  ...props
}: AmountFieldProps<T>) {
  const { field, fieldState } = useController({ name, control, rules, disabled })

  return (
    <>
      <NumoraInput {...props} {...field} aria-invalid={fieldState.invalid} />
      {fieldState.error && <span role="alert">{fieldState.error.message}</span>}
    </>
  )
}

// <AmountField name="amount" control={control} rules={{ required: 'Amount is required' }} locale="de-DE" />

The onChange event carries both strings. If you write the handler yourself, pass the raw value: onChange={(e) => field.onChange(e.target.value)}.

  • e.target.value is the raw value, "1000.50" in every locale
  • e.target.formattedValue is the display value, "1,000.50" in en-US

Complete example

A swap form with Max and Half buttons. Both write the amount with setValue(), as a string.

import { useForm, Controller } from 'react-hook-form'
import { NumoraInput } from 'numora-react'

interface FormValues {
  amount: string
}

function halve(amount: string, decimals = 6): string {
  const [int = '0', frac = ''] = (amount || '0').split('.')
  const units = BigInt(int + frac.padEnd(decimals, '0').slice(0, decimals)) / 2n
  const padded = units.toString().padStart(decimals + 1, '0')
  const result = `${padded.slice(0, -decimals)}.${padded.slice(-decimals)}`
  return result.replace(/\.?0+$/, '')
}

function SwapForm() {
  const { control, handleSubmit, setValue, getValues } = useForm<FormValues>({
    defaultValues: { amount: '' }
  })

  const handleMaxClick = () => {
    setValue('amount', '1000000')
  }

  // String-based halving: scale to integer units, halve with bigint, scale back.
  // Never route the amount through Number()/parseFloat().
  const handleHalfClick = () => {
    setValue('amount', halve(getValues('amount')))
  }

  return (
    <form onSubmit={handleSubmit((data) => console.log(data))}>
      <Controller
        control={control}
        name="amount"
        rules={{ required: 'Amount is required' }}
        render={({ field, fieldState: { error } }) => (
          <>
            <NumoraInput {...field} decimalMaxLength={6} placeholder="0.0" />
            {error && <span>{error.message}</span>}
          </>
        )}
      />
      <div>
        <button type="button" onClick={handleMaxClick}>Max</button>
        <button type="button" onClick={handleHalfClick}>Half</button>
      </div>
      <button type="submit">Submit</button>
    </form>
  )
}

Try it with any locale

A live form built with React Hook Form. Switch the locale and compare what the field shows with what the form holds. The form state is the same raw value in every locale.

Field shows
""
Form state (useWatch)
"1234567.89"
Submitted
(not submitted)
dirty / touched
false / false
The form state stays a plain decimal string (ASCII digits, . as the decimal mark) in every locale. Try typing, pasting a number copied from another app, and switching the locale mid-edit.

Why not register?

Don't spread register('amount') onto NumoraInput. register reads the value from the DOM node, and the DOM node holds the display value. The form stores "1,234.5", or "1.234,5" in de-DE, where you wanted "1234.5".

Writing is worse. setValue() and reset() put their string straight into the input, past Numora. In a de-DE field, setValue('amount', '1234.5') shows 1234.5. Type a 6 after it and the field reads 123.456, because the dot was taken for a thousand separator. Use Controller.