react-hook-form How can I pass field value to a parent component

ali*_*aha 3 reactjs react-redux react-hooks react-hook-form

I want to get the value of a field inside a react-hook-form component and print it outside the form. The value should be updated onChange. is there a way to use the useWatch outside the form component?

import React from "react";
import ReactDOM from "react-dom";
import { useForm, useWatch } from "react-hook-form";

import "./styles.css";

function Form() {
  const { register, control, handleSubmit } = useForm();
  return (
    <>
      <form onSubmit={handleSubmit((data) => console.log("data", data))}>
        <label>Name:</label>
        <input ref={register} name="name" />
        <p>{useWatch({ control, name: "name" })}</p>
      </form>
    </>
  );
}
function App() {
  return (
    <>
      <h1>The Value of the input should goes here</h1>
      <Form />
    </>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Run Code Online (Sandbox Code Playgroud)

Edit code here

Muh*_*wan 9

放入useForm()您的父组件,然后将其作为 props 传递给您的子组件

import React from "react";
import ReactDOM from "react-dom";
import { useForm, useWatch } from "react-hook-form";

import "./styles.css";

function Form({ form }) {
  const { register, handleSubmit } = form;
  return (
    <>
      <form onSubmit={handleSubmit((data) => console.log("data", data))}>
        <label>Name:</label>
        <input ref={register} name="name" />
      </form>
    </>
  );
}
function App() {
  const form = useForm();
  const { control } = form
  const name = useWatch({ control, name: "name" })
  return (
    <>
      <h1>{name}</h1>
      <Form form={form} />
    </>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Run Code Online (Sandbox Code Playgroud)

useFormContext()或者,您也可以在子组件内部使用,而不传递任何道具。该useFormContext()钩子将从父级或最近祖先的上下文中获取上下文useForm()

import React from "react";
import ReactDOM from "react-dom";
import { useForm, useWatch, useFormContext } from "react-hook-form";

import "./styles.css";

function Form() {
  const { register, handleSubmit } = useFormContext();
  return (
    <>
      <form onSubmit={handleSubmit((data) => console.log("data", data))}>
        <label>Name:</label>
        <input ref={register} name="name" />
      </form>
    </>
  );
}
function App() {
  const { control } = useForm();
  const name = useWatch({ control, name: "name" })
  return (
    <>
      <h1>{name}</h1>
      <Form />
    </>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Run Code Online (Sandbox Code Playgroud)