sth8119
sth8119

Reputation: 413

How to pass an object to onSubmit in React Hook Form

When using react-hook-form I need to pass arbitrary data into the onSubmit function. Example code:

function App() {
  const { register, handleSubmit } = useForm();
  const navigation = { foo: 'bar' }; // object to pass
  const onSubmit = (data) => {
    // how to access navigation here?
    console.log(data);
    console.log(navigation); // undefined
  }; 
  return (
    <form onSubmit={handleSubmit(onSubmit)}> // <<== pass navigation here as arg? 
      <input defaultValue="test" {...register("example")} />
      <input type="submit" />
    </form>
  );
}

How can I pass my object navigation into onSubmit?

Upvotes: 13

Views: 11652

Answers (3)

You could do smth like this.

const onSubmit = (obj) => (formData) => { 
  console.log(obj);
};

<form onSubmit={handleSubmit(onSubmit(obj))}> // your obj

Upvotes: 3

Ed Rebolledo
Ed Rebolledo

Reputation: 3

Hi I guess that the navigation props is received by the App Component (like a prop) and then you can pass it to the onSubmit method.

try this:

"onSubmit={()=>handleSubmit(props.navigation)}"

here an explample https://reactnavigation.org/docs/navigation-prop/

Upvotes: 0

Taki
Taki

Reputation: 17654

handleSubmit(onSubmit) means that you're passing onSubmit by reference and it's taking the data by default , call the handleSubmit like this :

<form onSubmit={handleSubmit(data => onSubmit(data, navigation))}>

and the object should be available here :

const onSubmit = (data, obj) => {
  console.log(data, obj);
};

Upvotes: 18

Related Questions