L.Diaz
L.Diaz

Reputation: 51

Copy form input from another Component's form - React Hook Form

I have two React components that have identical form fields. There is a checkbox that should mirror the input from the form in the other component if it is checked.

The same concept as "same address as billing" functionality but the forms are in separate components.

I'm trying to use React Hook Form's "watch" but I'm not sure how to pass the input from Component: FormOne to Component: FormTwo.

Here's my code: Code Sandbox

Upvotes: 1

Views: 2331

Answers (1)

knoefel
knoefel

Reputation: 6949

As you are using useForm multiple times, you can't use RHF's provided <FormProvider />.

So basically you have the following options:

  • refactor your <Form /> components, that they all will use the same methods returned by useForm by using RHF's <FormProvider /> instead of defining useForm for every <Form /> component.
  • use React's Context API so you can access the form state in every child <Form /> component
  • pass values and setters using props

Here is a CodeSandbox using RHF's <FormProvider />:

Edit condescending-antonelli-18wv3

Here is a CodeSandbox using Context API:

Edit gallant-sea-irdbc

Upvotes: 1

Related Questions