Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 307
sth8119 Avatar asked Mar 02 '23 15:03

sth8119


1 Answers

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);
};
like image 153
Taki Avatar answered Mar 04 '23 08:03

Taki