I am trying to use a react hook form to create a screen in my react native app. I need to pass my navigation object to my submit function for my routing to work. Here is the example using code from React Hook Form:
function App() { const { register, handleSubmit, formState: { errors } } = useForm(); const onSubmit = (data) => { //Want to be able to access the object here when it is passed as a parameter console.log(data); }; const navigation = {myObject: "My object"}; //Want to pass this to the onSubmit function from the onSubmit call in the form return ( <form onSubmit={handleSubmit(onSubmit)}> //Want to pass the object to the function here <input defaultValue="test" {...register("example")} /> <input type="submit" /> </form> ); }
*Took code out for clarity.
So, how can I pass my object into the “onSubmit={handleSubmit(onSubmit)}”?
Answer
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); };