Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
43
rated 0 times [  47] [ 4]  / answers: 1 / hits: 6323  / 3 Years ago, wed, april 7, 2021, 12:00:00

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?


More From » reactjs

 Answers
4

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);
};

[#1507] Sunday, April 4, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jensenb

Total Points: 634
Total Questions: 102
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Thu, Jun 24, 2021
3 Years ago
jensenb questions
Fri, Dec 10, 21, 00:00, 3 Years ago
Thu, Jun 24, 21, 00:00, 3 Years ago
Tue, Jun 4, 19, 00:00, 5 Years ago
Mon, Mar 25, 19, 00:00, 5 Years ago
Thu, Feb 21, 19, 00:00, 5 Years ago
;