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
?
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);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With