use-form

use-form hook options and returned form object

License

Examples

This page is the useForm reference. Complete forms that combine several features, with full code, are available on a separate page:

Open form examples page

Usage

The useForm hook returns a form object with values, errors, validation and submission handlers. Installation and a walkthrough of the example below are on the Get started page:

import { Button, Checkbox, Group, TextInput } from '@mantine/core';
import { useForm } from '@mantine/form';

function Demo() {
  const form = useForm({
    initialValues: {
      email: '',
      termsOfService: false,
    },

    validate: {
      email: (value) => (/^\S+@\S+$/.test(value) ? null : 'Invalid email'),
    },
  });

  return (
    <form onSubmit={form.onSubmit((values) => console.log(values))}>
      <TextInput
        withAsterisk
        label="Email"
        placeholder="your@email.com"
        {...form.getInputProps('email')}
      />

      <Checkbox
        mt="md"
        label="I agree to sell my privacy"
        {...form.getInputProps('termsOfService', { type: 'checkbox' })}
      />

      <Group justify="flex-end" mt="md">
        <Button type="submit">Submit</Button>
      </Group>
    </form>
  );
}

Options

All options are optional. Options are read on every render, you can pass values that depend on props or state.

  • mode – uncontrolled (default) or controlled, see Form modes
  • initialValues – initial form values, define the shape and type of the form, see Form values
  • initialErrors, initialTouched, initialDirty – initial errors and field status
  • validate – rules object, function or schema, see Form validation
  • validateInputOnChange, validateInputOnBlur – validate fields on change or blur, true or an array of field paths
  • clearInputErrorOnChange – clear field error when its value changes, true by default
  • validateDebounce – debounce in ms for async validation triggered on change or blur
  • resolveValidationError – converts an error thrown by an async rule to an error message
  • transformValues – transforms values before they are passed to the submit handler, see Form submission
  • onSubmitPreventDefault – always (default), never or validation-failed
  • onValuesChange – called with new and previous values on every change, see Watching values
  • cascadeUpdates – notify nested field watchers when form.setFieldValue or an input sets a parent path, false by default
  • enhanceGetInputProps – adds props to the object returned by form.getInputProps, see getInputProps
  • touchTrigger – change (default) or focus, see Form status
  • name – form name for form actions

Form object

All examples below use the following form:

import { useForm } from '@mantine/form';

const form = useForm({
  initialValues: {
    path: '',
    path2: '',
    user: {
      firstName: 'John',
      lastName: 'Doe',
    },
    fruits: [
      { name: 'Banana', available: true },
      { name: 'Orange', available: false },
    ],
    accepted: false,
  },
});

Values

Form values guide

// Current form values, always up to date in both modes
form.getValues();

// Values snapshot from the last render, stale in uncontrolled mode
form.values;

// Set all form values, the payload is shallow merged with the current values
form.setValues(values);

// Set form values using the previous state
form.setValues((prev) => ({ ...prev, ...values }));

// Set the value of a single field
form.setFieldValue('path', value);

// Set the value of a nested field
form.setFieldValue('user.firstName', 'Jane');

// Update the subscribed input without rerendering the form component
form.setFieldValue('path', value, { forceUpdate: false });

// Set initialValues and values once, ignored on subsequent calls
form.initialize(values);

// True after form.initialize was called
form.initialized;

// Reset values to initialValues, clear errors, touched and dirty state
form.reset();

// Reset the field at the given path to its initial value
form.resetField('path');

// Set initial values used by form.reset and dirty checks
form.setInitialValues({ values: 'object' });

// Current initial values
form.getInitialValues();

// Values transformed with the transformValues option
form.getTransformedValues();

Inputs

getInputProps guide

// Props for an input: value, onChange, onFocus, onBlur, error
form.getInputProps('path');

// Props for a checkbox: checked instead of value
form.getInputProps('accepted', { type: 'checkbox' });

// Props for a radio option
form.getInputProps('path', { type: 'radio', value: 'option' });

// DOM node of the input with the given path
form.getInputNode('path');

// Focus the input or a focusable control inside a group
form.focusInput('path');

// Field object for the path, same shape as useField return value
form.getField('path');
form.getField('accepted', { type: 'checkbox' });

Watchers

Watching values guide

// Run an effect when the field changes
form.watch('path', ({ previousValue, value, touched, dirty }) => {});

// Subscribe the component to the field value, rerenders when it changes
const value = form.useWatchValue('path');

List items

Nested fields and lists guide

// Insert an item at the end of the list
form.insertListItem('fruits', { name: 'Apple', available: true });

// Insert an item at the given index
form.insertListItem('fruits', { name: 'Orange', available: true }, 1);

// Remove the item at the given index
form.removeListItem('fruits', 1);

// Replace the item at the given index
form.replaceListItem('fruits', 1, { name: 'Apple', available: true });

// Move the item from one index to another
form.reorderListItem('fruits', { from: 1, to: 0 });

Validation

Form validation guide

// Validate all fields, set form.errors, return { hasErrors, errors }
form.validate();

// Validate a single field, set its error, return { hasError, error }
form.validateField('user.firstName');

// Same as form.validate and form.validateField but do not set errors, return boolean
form.isValid();
form.isValid('user.firstName');

// Validation results are returned directly with sync rules
// and wrapped in a Promise when any rule is async
await form.validate();

// True while any async validation is running
form.validating;

// True while async validation of the given field is running
form.isValidating('path');

Errors

Form errors guide

// Current errors
form.errors;

// Set all errors
form.setErrors({ path: 'Error message', path2: 'Another error' });

// Set the error of a single field
form.setFieldError('user.lastName', 'No special characters allowed');

// Clear all errors
form.clearErrors();

// Clear the error of a single field
form.clearFieldError('path');

Submission

Form submission guide

// Form element onSubmit handler: validates the form,
// calls handleSubmit with transformed values when validation passes
// and handleValidationFailure with errors when it fails
<form onSubmit={form.onSubmit(handleSubmit, handleValidationFailure)} />;

// Form element onReset handler, calls form.reset
<form onReset={form.onReset} />;

// True while the promise returned from handleSubmit is pending
form.submitting;

// Set submitting state manually
form.setSubmitting(true);

Touched and dirty

Form status guide

// True if the user interacted with any field in the form
form.isTouched();

// True if the user interacted with the given field
form.isTouched('path');

// True if form values are not deep equal to initial values
form.isDirty();

// True if the field value is not deep equal to its initial value
form.isDirty('path');

// Subscribe the component to touched and dirty state, rerenders when it changes
const dirty = form.useDirty();
const touched = form.useTouched('path');

// Touched and dirty state of all fields
form.getTouched();
form.getDirty();

// Set touched and dirty state of fields
form.setTouched({ 'user.firstName': true, 'user.lastName': false });
form.setDirty({ 'user.firstName': true, 'user.lastName': false });

// Clear touched state of all fields
form.resetTouched();

// Clear dirty state of all fields, next dirty checks compare
// values to the current values instead of initial values
form.resetDirty();

Types

UseFormReturnType, TransformedValues, FormErrors, FormPath and useForm generics are described on the use-form types page.