Form context

Add context support to use-form with createFormContext

Usage

createFormContext function creates context provider and hook to get form object from context:

import { createFormContext } from '@mantine/form';
import { TextInput } from '@mantine/core';

// Definition of form values is required
interface FormValues {
  age: number;
  name: string;
}

// createFormContext returns a tuple with 3 items:
// FormProvider is a component that sets form context
// useFormContext hook return form object that was previously set in FormProvider
// useForm hook works the same way as useForm exported from the package but has predefined type
const [FormProvider, useFormContext, useForm] = createFormContext<FormValues>();

function ContextField() {
  const form = useFormContext();
  return <TextInput label="Your name" {...form.getInputProps('name')} />;
}

export function Context() {
  // Create form as described in use-form documentation
  const form = useForm({
    initialValues: {
      age: 0,
      name: '',
    },
  });

  // Wrap your form with FormProvider
  return (
    <FormProvider form={form}>
      <form onSubmit={form.onSubmit(() => {})}>
        <ContextField />
      </form>
    </FormProvider>
  );
}

Store context in separate file

Usually it is a good idea to store form context in separate file to avoid dependencies cycle:

// form-context.ts file
import { createFormContext } from '@mantine/form';

interface UserFormValues {
  age: number;
  name: string;
}

// You can give context variables any name
export const [UserFormProvider, useUserFormContext, useUserForm] =
  createFormContext<UserFormValues>();

Then you can import context variables from anywhere:

// NameInput.tsx
import { TextInput } from '@mantine/core';
import { useUserFormContext } from './form-context';

export function NameInput() {
  const form = useUserFormContext();
  return <TextInput label="Name" {...form.getInputProps('name')} />;
}
// UserForm.tsx
import { NumberInput } from '@mantine/core';
import { UserFormProvider, useUserForm } from './form-context';
import { NameInput } from './NameInput';

function UserForm() {
  const form = useUserForm({
    initialValues: {
      age: 0,
      name: '',
    },
  });

  return (
    <UserFormProvider form={form}>
      <form onSubmit={form.onSubmit(() => {})}>
        <NumberInput label="Age" {...form.getInputProps('age')} />
        <NameInput />
      </form>
    </UserFormProvider>
  );
}