API Reference / FormProvider

FormProvider

A React component that renders a Context Provider for the form context. It is required if you want to use useField or useFormMetadata hook.

1import { FormProvider, useForm } from '@conform-to/react';
2
3export default function SomeParent() {
4  const [form, fields] = useForm();
5
6  return <FormProvider context={form.context}>{/* ... */}</FormProvider>;
7}

#Props

context

The form context. It is created with useForm and can be accessed through form.context.

#Tips

FormProvider does not need to be a direct parent of the form

You are free to put your inputs anywhere outside of the form as long as they are associated through the form attribute.

1function Example() {
2  const [form, fields] = useForm();
3  return (
4    <FormProvider context={form.context}>
5      <div>
6        <form id={form.id} />
7      </div>
8      <div>
9        <input name={fields.title.name} form={form.id} />
10      </div>
11    </FormProvider>
12  );
13}

FormProvider can be nested

This is useful if you need to have one form inside another due to layout constraints.

1import { FormProvider, useForm } from '@conform-to/react';
2
3function Field({ name, formId }) {
4  //  useField will look for the closest FormContext if no formId is provided
5  const [meta] = useField(name, { formId });
6
7  return <input name={meta.name} form={meta.form} />;
8}
9
10function Parent() {
11  const [form, fields] = useForm({ id: 'parent' });
12  return (
13    <FormProvider context={form.context}>
14      <form id={form.id} />
15
16      <Field name={fields.category.name} />
17      <Child />
18    </FormProvider>
19  );
20}
21
22function Child() {
23  const [form, fields] = useForm({ id: 'child' });
24
25  return (
26    <FormProvider context={form.context}>
27      <form id={form.id} />
28      <Field name={fields.title.name} />
29
30      {/* This will look for the form context with the id 'parent' instead */}
31      <Field name={fields.bar.name} formId="parent" />
32    </FormProvider>
33  );
34}