Get the values in the form, from a component outside the form

Viewed 1109

I've a component that is built using react-hook-form. I'm trying access the value in form, through a button that is sibling of the Form component. Basically the getvalue function should somehow get the values in the form.

Form.tsx

export default function Form({ onSubmit }) {
    const { register, handleSubmit } = useForm({
     defaultValues: {
       firstName: "bill",
       lastName: "luo",
       email: "bluebill1049@hotmail.com"
     }
    });
 
 return (  
   <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("firstName")} />
      <input {...register("lastName")} />
      <input {...register("email")} />

      <button type="submit">Submit</button>
    </form>
   )
}

App.tsx

const onSubmit = data => console.log(data);
const getValue = ???

function App() {
   return (
      <Form onSubmit={onSubmit}/>
    
      <button onClick={getValue} />
   )

}

I want to get the form data values in getValue

1 Answers

You could use onChange to set the values in the form

<Form onSubmit={onSubmit} geValue={getValue}/>

and inside the Form.tsx

   <form onSubmit={handleSubmit(onSubmit)} onChange={handleChange(getValue)}>

however i'm not really sure if this would work for you - can you elaborate more about what you are trying to do, maybe we can help you better.

Also, you should only pass callbacks to onSubmit and onChange so probably this is the correct syntax for that <form onSubmit={(e) => handleSubmit(e, onSubmit)} onChange={(e) => handleChange(e, getValue)}>

Related