How to get useForm data in react component when input fields are in child component?

Viewed 1568

How can I get data from child components using useForm in the parent component? All my components are react-hooks.

I tried:

SignUp.js:

  const { register, handleSubmit } = useForm();

  const submitHandler = (data) => {
    console.log(data);
  };
  return (
    <div style={{ margin: "3rem" }}>
      <form onSubmit={handleSubmit(submitHandler)}>
        <Form register={register}>
        <button type="submit">Sign Up</button>
      </form>
    </div>

Form.js:

return(
  <div>
   <input name="username" ref={props.register}/>
  </div>
)

But when I click on submit button I get an empty object {} in the console. Is this the right way or should I add something else?

1 Answers

I got to know about setValue from https://react-hook-form.com/faqs

SignUp.js:

const { register, handleSubmit, setValue, setError } = useForm();

useEffect(() => {
register({ name: "username" });
register({ name: "first_name" });
register({ name: "last_name" });
}

  const submitHandler = (data) => {
    console.log(data);
  };
  return (
    <div style={{ margin: "3rem" }}>
      <form onSubmit={handleSubmit(submitHandler)}>
        <Form setValue={setValue}>
        <button type="submit">Sign Up</button>
      </form>
    </div>
  )

Form.js:

return(
  <div>
   <input 
     name="username" 
     onChange={(e) => props.setValue("username", e.target.value)}/>
   <input 
     name="first_name" 
     onChange={(e) => props.setValue("first_name", e.target.value)}/>
   <input 
     name="last_name" 
     onChange={(e) => props.setValue("last_name", e.target.value)}/>
  </div>
)
Related