### Install and run React Hook Form documentation Source: https://github.com/react-hook-form/documentation/blob/master/README.md Install project dependencies and start the development server using pnpm package manager. ```shellscript pnpm install && pnpm dev ``` -------------------------------- ### Install Dependencies and Start Dev Server Source: https://github.com/react-hook-form/documentation/blob/master/CONTRIBUTING.md Commands to install project dependencies and launch the local development environment using pnpm. This allows for real-time previewing of documentation changes. ```shellscript pnpm install pnpm run dev ``` -------------------------------- ### Install React Hook Form Source: https://github.com/react-hook-form/documentation/blob/master/src/content/get-started.mdx Use npm to install the React Hook Form library. ```bash npm install react-hook-form ``` -------------------------------- ### Install React Hook Form V8 (Beta) Source: https://github.com/react-hook-form/documentation/blob/master/src/content/migrate-v7-to-v8.mdx Use npm to install the beta version of React Hook Form V8. ```bash npm install react-hook-form@beta ``` -------------------------------- ### Setup Jest Configuration Source: https://github.com/react-hook-form/documentation/blob/master/src/content/advanced-usage.mdx Update your jest.config.js to include the setup file after environment setup. This ensures testing libraries are available. ```javascript module.exports = { setupFilesAfterEnv: ["/setup.js"], // or .ts for TypeScript App // ...other settings } ``` -------------------------------- ### Setup Jest for Testing Source: https://github.com/react-hook-form/documentation/blob/master/src/content/advanced-usage.mdx Configure Jest to use a setup file that imports @testing-library/jest-dom for testing React Hook Form applications. ```javascript import "@testing-library/jest-dom" ``` -------------------------------- ### Basic useFieldArray Example (JS/TS) Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/usefieldarray.mdx A fundamental example demonstrating the integration of `useFieldArray` within a React Hook Form setup. It includes fields for first and last names, append functionality, and submission. ```javascript import { useForm, useFieldArray } from "react-hook-form" function App() { const { register, control, handleSubmit, reset, trigger, setError } = useForm( { // defaultValues: {}; you can populate the fields by this attribute } ) const { fields, append, remove } = useFieldArray({ control, name: "test", }) return (
console.log(data))}>
) } ``` -------------------------------- ### Set up Routes and State Store Source: https://github.com/react-hook-form/documentation/blob/master/src/content/advanced-usage.mdx Configure your application's routes and initialize the state store for the wizard form. This example uses react-router-dom for routing and little-state-machine for state management. ```javascript import { BrowserRouter, Routes, Route } from "react-router-dom" import { createStore } from "little-state-machine" import Step1 from "./Step1" import Step2 from "./Step2" import Result from "./Result" createStore({ data: { firstName: "", lastName: "", }, }) export default function App() { return ( } /> } /> } /> ) } ``` -------------------------------- ### UseFormReturn Example with Custom Components Source: https://github.com/react-hook-form/documentation/blob/master/src/content/ts.mdx Illustrates how to use the 'UseFormReturn' type in a practical React application, integrating custom input components and demonstrating form submission with 'useForm'. ```tsx import type { FieldValues, UseFormReturn, SubmitHandler } from "react-hook-form" import { useForm } from "react-hook-form" type InputProps = React.DetailedHTMLProps< React.InputHTMLAttributes, HTMLInputElement > const Input = React.forwardRef((props, ref) => ( )) type Option = { label: React.ReactNode value: string | number | string[] } type SelectProps = React.DetailedHTMLProps< React.SelectHTMLAttributes, HTMLSelectElement > & { options: Option[] } const Select = React.forwardRef( ({ options, ...props }, ref) => ( ) ) type FormProps = { onSubmit: SubmitHandler children: (methods: UseFormReturn) => React.ReactNode } const Form = ({ onSubmit, children, }: FormProps) => { const methods = useForm() return (
{children(methods)}
) } type FormValues = { firstName: string lastName: string sex: string } export default function App() { const onSubmit = (data: FormValues) => console.log(data) return ( onSubmit={onSubmit}> {({ register }) => ( <> )} ) } ``` -------------------------------- ### Using FormProvider with useForm and useFormContext Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/formprovider.mdx This example demonstrates how to use FormProvider to share useForm methods across deeply nested components. It shows how to initialize useForm, wrap the form with FormProvider, and consume methods in a nested component using useFormContext. It also includes an example of resetting form values with useEffect. ```javascript import { useForm, FormProvider, useFormContext } from "react-hook-form" export default function App() { const methods = useForm() const onSubmit = (data) => console.log(data) const { register, reset } = methods useEffect(() => { reset({ name: "data", }) }, [reset]) // ❌ never put `methods` as the deps return ( // pass all methods into the context
) } function NestedInput() { const { register } = useFormContext() // retrieve all hook methods return } ``` -------------------------------- ### Smart Form Component Example Source: https://github.com/react-hook-form/documentation/blob/master/src/content/advanced-usage.mdx Example of using the smart Form component with Input and Select elements. This component automatically collects form data. ```javascript import { Form, Input, Select } from "./Components" export default function App() { const onSubmit = (data) => console.log(data) return (
) } ``` -------------------------------- ### useFormContext with FormProvider and nested components Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useformcontext.mdx Complete example showing FormProvider setup with useFormContext in nested components. Wrap your form with FormProvider and use useFormContext to access form methods in child components without prop drilling. ```javascript import { useForm, FormProvider, useFormContext } from "react-hook-form" export default function App() { const methods = useForm() const onSubmit = (data) => console.log(data) const { register, reset } = methods useEffect(() => { reset({ name: "data", }) }, [reset]) // ❌ never put `methods` as the deps return ( // pass all methods into the context
) } function NestedInput() { const { register } = useFormContext() // retrieve all hook methods return } ``` -------------------------------- ### Registering Input with useController Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/usecontroller.mdx This example shows the correct way to register an input using useController. It highlights that useController handles the registration process, and attempting to register the same input again with `register` will lead to conflicts. ```javascript const { field } = useController({ name: 'test' }) // ✅ // ❌ double up the registration ``` -------------------------------- ### Install Jest DOM Source: https://github.com/react-hook-form/documentation/blob/master/src/content/advanced-usage.mdx Install @testing-library/jest-dom to enhance Jest's capabilities for testing DOM interactions, which is necessary for React Hook Form's MutationObserver. ```bash npm install -D @testing-library/jest-dom ``` -------------------------------- ### Registering Form Fields for getValues Examples Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform/getvalues.mdx Registers two input fields using `register` to provide a basic form structure for subsequent `getValues` method demonstrations. ```jsx ``` -------------------------------- ### Basic Usage with useLens and useFieldArray Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/uselens.mdx Complete example showing how to set up a form with nested arrays using useLens, compose reusable components with lens.focus() and lens.reflect(), and integrate with useFieldArray via lens.interop(). ```tsx import { useForm } from "react-hook-form" import { Lens, useLens } from "@hookform/lenses" import { useFieldArray } from "@hookform/lenses/rhf" function FormComponent() { const { handleSubmit, control } = useForm<{ firstName: string lastName: string children: { name: string surname: string }[] }>({}) const lens = useLens({ control }) return (
({ name: firstName, surname: lastName, }))} /> ) } function ChildForm({ lens, }: { lens: Lens<{ name: string; surname: string }[]> }) { const { fields, append } = useFieldArray(lens.interop()) return ( <> {lens.map(fields, (value, l) => ( ))} ) } // PersonForm is used twice with different sources function PersonForm({ lens, }: { lens: Lens<{ name: string; surname: string }> }) { return (
) } function StringInput({ lens }: { lens: Lens }) { return ctrl.register(name))} /> } ``` -------------------------------- ### Shopping Cart Example with useFieldArray Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/usefieldarray.mdx Demonstrates a shopping cart where users can add, remove, and update items. It uses useFieldArray to manage the cart items and useWatch to calculate the total price dynamically. ```tsx import * as React from "react" import { useForm, useFieldArray, useWatch, Control } from "react-hook-form" type FormValues = { cart: { name: string price: number quantity: number }[] } const Total = ({ control }: { control: Control }) => { const formValues = useWatch({ name: "cart", control, }) const total = formValues.reduce( (acc, current) => acc + (current.price || 0) * (current.quantity || 0), 0 ) return

Total Amount: {total}

} export default function App() { const { register, control, handleSubmit, formState: { errors }, } = useForm({ defaultValues: { cart: [{ name: "test", quantity: 1, price: 23 }], }, mode: "onBlur", }) const { fields, append, remove } = useFieldArray({ name: "cart", control, }) const onSubmit = (data: FormValues) => console.log(data) return (
{fields.map((field, index) => { return (
) })}
) } ``` -------------------------------- ### Complete getFieldState example in a React component Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform/getfieldstate.mdx This example demonstrates integrating `getFieldState` within a React component. It shows registering an input, displaying `isDirty` and `isTouched` states, and logging the full field state. ```javascript import * as React from "react" import { useForm } from "react-hook-form" export default function App() { const { register, getFieldState, formState: { isDirty, isValid }, } = useForm({ mode: "onChange", defaultValues: { firstName: "", }, }) // you can invoke before render or within the render function const fieldState = getFieldState("firstName") return (
{" "}

{getFieldState("firstName").isDirty && "dirty"}

{" "}

{getFieldState("firstName").isTouched && "touched"}

) } ``` -------------------------------- ### Calling unregister with various arguments Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform/unregister.mdx These examples illustrate different ways to call the `unregister` method, demonstrating how to unregister a group of inputs, a specific nested input, or an array of inputs. ```javascript unregister("yourDetails") ``` ```javascript unregister("yourDetails.firstName") ``` ```javascript unregister(["yourDetails.lastName"]) ``` -------------------------------- ### Basic Form with Validation Source: https://github.com/react-hook-form/documentation/blob/master/src/content/advanced-usage.mdx A standard form setup using React Hook Form for input registration and validation. It demonstrates handling required and max length constraints. ```javascript import { useForm } from "react-hook-form" export default function App() { const { register, handleSubmit, formState: { errors }, } = useForm() const onSubmit = (data) => console.log(data) return (
{errors.name && errors.name.type === "required" && ( This is required )} {errors.name && errors.name.type === "maxLength" && ( Max length exceeded )}
) } ``` -------------------------------- ### Install Yup resolver for React Hook Form Source: https://github.com/react-hook-form/documentation/blob/master/src/content/get-started.mdx This command installs the necessary packages to integrate Yup for schema-based validation with React Hook Form. ```bash npm install @hookform/resolvers yup ``` -------------------------------- ### Install @hookform/lenses with npm Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/uselens.mdx Use npm to add the @hookform/lenses package to your project dependencies. ```bash npm install @hookform/lenses ``` -------------------------------- ### Basic setValue Usage in JavaScript Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform/setvalue.mdx This example demonstrates the basic usage of `setValue` to update a form field. It also shows how to use `setValue` with options like `shouldValidate` and `shouldDirty`. ```javascript import { useForm } from "react-hook-form" const App = () => { const { register, setValue } = useForm({ firstName: "", }) return (
) } ``` -------------------------------- ### Form Component with onSubmit Callback Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform/form.mdx Example of providing an `onSubmit` callback to the Form component, which is invoked after successful validation. ```javascript
mutation(data)} /> ``` -------------------------------- ### Track `isDirty` state with `useForm` and `setValue` Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform/formstate.mdx This example demonstrates how `isDirty` reflects changes when `setValue` is used, and how it resets when the value matches `defaultValues`. Ensure `defaultValues` are provided to `useForm` for accurate tracking. ```javascript const { formState: { isDirty, dirtyFields }, setValue } = useForm({ defaultValues: { test: "" } }) // isDirty: true ✅ setValue('test', 'change') // isDirty: false because there getValues() === defaultValues ❌ setValue('test', '') ``` -------------------------------- ### Handle Submit with Async Validation and Submission Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform/handlesubmit.mdx Use this example for asynchronous form submissions, including a delay and conditional logic. It shows how to handle potential errors during the async operation. ```javascript import { useForm } from "react-hook-form" const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) function App() { const { register, handleSubmit, formState: { errors }, } = useForm() const onSubmit = async (data) => { await sleep(2000) if (data.username === "bill") { alert(JSON.stringify(data)) } else { alert("There is an error") } } return (
) } ``` -------------------------------- ### Watching a Specific Field Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/usewatch.mdx This example demonstrates how to use useWatch to subscribe to a single field ('firstName') and display its current value. It also shows how to set a default value before the form is mounted. ```tsx import { useForm, useWatch } from "react-hook-form" interface FormInputs { firstName: string lastName: string } function FirstNameWatched({ control }: { control: Control }) { const firstName = useWatch({ control, name: "firstName", // without supply name will watch the entire form, or ['firstName', 'lastName'] to watch both defaultValue: "default", // default value before the render }) return

Watch: {firstName}

// only re-render at the custom hook level, when firstName changes } function App() { const { register, control, handleSubmit } = useForm() const onSubmit = (data: FormInputs) => { console.log(data) } return (
) } ``` -------------------------------- ### Controller with Input Transformation Source: https://github.com/react-hook-form/documentation/blob/master/src/content/advanced-usage.mdx Use the Controller component to integrate custom input transformation logic for parsing and formatting values. This example demonstrates how to handle string-to-number conversions and default empty states for numeric inputs. ```javascript import { Controller } from "react-hook-form" const ControllerPlus = ({ control, transform, name, defaultValue }) => ( ( field.onChange(transform.output(e))} value={transform.input(field.value)} /> )} /> ) // usage below: (isNaN(value) || value === 0 ? "" : value.toString()), output: (e) => { const output = parseInt(e.target.value, 10) return isNaN(output) ? 0 : output }, }} control={control} name="number" defaultValue="" /> ``` -------------------------------- ### Resetting Form Values and Errors Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform/reset.mdx This example demonstrates how to use the `reset` function to clear both form values and errors. It also shows how to reset the form to its initial state using a button. ```tsx import { useForm } from "react-hook-form" interface UseFormInputs { firstName: string lastName: string } export default function Form() { const { register, handleSubmit, reset, formState: { errors }, } = useForm() const onSubmit = (data: UseFormInputs) => { console.log(data) } return (
reset()} value="Custom Reset Field Values & Errors" />
) } ``` -------------------------------- ### Dynamic Form with Nested UseFieldArray and UseWatch Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/usefieldarray.mdx This example showcases managing a dynamic array of fields where each item is an editable component. It uses useFieldArray for the array structure and useWatch to display live previews of the edited data. ```javascript import * as React from "react" import { useForm, useFieldArray, useWatch } from "react-hook-form" export default function App() { const { control, handleSubmit } = useForm() const { fields, append, update } = useFieldArray({ control, name: "array", }) return (
console.log(data))}> {fields.map((field, index) => ( ))} ) } const Display = ({ control, index }) => { const data = useWatch({ control, name: `array.${index}`, }) return

{data?.firstName}

} const Edit = ({ update, index, value, control }) => { const { register, handleSubmit } = useForm({ defaultValues: value, }) return (
) } ``` -------------------------------- ### Custom Register for Modal/Tab Forms with State Management Source: https://github.com/react-hook-form/documentation/blob/master/src/content/faqs.mdx This example shows how to use custom registration with `useEffect` and `setValue` to manage input state in modals or tabs. It utilizes `watch` to track input values and `handleSubmit` for form submission. ```javascript import React, { useEffect } from "react" import { useForm } from "react-hook-form" function App() { const { register, watch, setValue, handleSubmit } = useForm({ defaultValues: { firstName: "", lastName: "", }, }) const { firstName, lastName } = watch() useEffect(() => { register("firstName") register("lastName") }, [register]) const handleChange = (e, name) => { setValue(name, e.target.value) } const onSubmit = (data) => console.log(data) return (
handleChange(e, "firstName")} value={firstName} /> handleChange(e, "lastName")} value={lastName} />
) } ``` -------------------------------- ### Clone and Branch for React Hook Form Docs Source: https://github.com/react-hook-form/documentation/blob/master/CONTRIBUTING.md Initial steps to clone the documentation repository and create a feature branch for development. Requires Git installed locally. ```shellscript git clone https://github.com/YOUR_GITHUB_USERNAME/website.git git checkout -b your-meaningful-branch-name ``` -------------------------------- ### Setting up createFormControl with useForm Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/createFormControl.mdx Demonstrates how to initialize `createFormControl` and integrate its `formControl` with `useForm` and other hooks like `useFormState`. ```javascript const { formControl, control, handleSubmit, register } = createFormControl({ mode: 'onChange', defaultValues: { firstName: 'Bill' } }) function App() { useForm({ formControl, }) return (
console.log)}> ); } function FormState() { useFormState({ control // no longer need context api }) } function Controller() { useFormState({ control // no longer need context api }) } ``` -------------------------------- ### Controller with React Datepicker (v7) Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/usecontroller/controller.mdx This example shows the integration of React Datepicker with React Hook Form (v7) using the Controller component. The setup is similar to v6, highlighting the core functionality for controlled inputs. ```javascript import ReactDatePicker from "react-datepicker" import { TextField } from "@material-ui/core" import { useForm, Controller } from "react-hook-form" function App() { const { handleSubmit, control } = useForm() return (
console.log(data))}> ( )} /> ) } ``` -------------------------------- ### Controller with React Datepicker (v6) Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/usecontroller/controller.mdx This example demonstrates how to use the Controller component to integrate the React Datepicker library with React Hook Form (v6). It shows the basic setup for managing the date input's state and events. ```tsx import ReactDatePicker from "react-datepicker" import { TextField } from "@material-ui/core" import { useForm, Controller } from "react-hook-form" type FormValues = { ReactDatepicker: string } function App() { const { handleSubmit, control } = useForm() return (
console.log(data))}> ( )} /> ) } ``` -------------------------------- ### Accessing Errors with Lodash get Source: https://github.com/react-hook-form/documentation/blob/master/src/content/advanced-usage.mdx Utilize the lodash 'get' function for robust access to nested error properties, providing a fallback for undefined paths. ```javascript get(errors, 'firstName.message') ``` -------------------------------- ### Basic Form Component Usage Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform/form.mdx Demonstrates the basic usage of the Form component with action, method, and callback props for submission handling. ```javascript
{}} onSuccess={() => {}} onError={() => {}} validateStatus={(status) => status >= 200} /> ``` -------------------------------- ### Build and Test Production Site Locally Source: https://github.com/react-hook-form/documentation/blob/master/CONTRIBUTING.md Commands to generate a production-ready build of the documentation and serve it locally for final verification before submission. ```shellscript pnpm run build pnpm run start ``` -------------------------------- ### Basic Form Submission with handleSubmit Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform/form.mdx Demonstrates how to use `handleSubmit` with a custom `onSubmit` function to prepare or omit submission data. Also shows direct submission using the Form component. ```javascript const { handleSubmit, control } = useForm(); const onSubmit =(data) => callback(prepareData(data)) // or { console.log(data) }} /> ``` -------------------------------- ### Usage Rules for createFormControl Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/createFormControl.mdx Illustrates the correct way to use methods returned by `createFormControl` directly, and highlights that `FormProvider` is not needed. ```tsx const props = createFormControl() // ❌ You don't need provider // ✅ Direct use method from createFormControl ``` -------------------------------- ### Joi Resolver for React Hook Form Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform.mdx Integrates Joi schema validation with React Hook Form. Ensure Joi and @hookform/resolvers/joi are installed. ```tsx import { useForm } from "react-hook-form" import { joiResolver } from "@hookform/resolvers/joi" import Joi from "joi" interface IFormInput { name: string age: number } const schema = Joi.object({ name: Joi.string().required(), age: Joi.number().required(), }) const App = () => { const { register, handleSubmit, formState: { errors }, } = useForm({ resolver: joiResolver(schema), }) const onSubmit = (data: IFormInput) => { console.log(data) } return ( ) } ``` -------------------------------- ### Form Component with Custom Headers Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform/form.mdx Example of providing custom request headers to the Form component, useful for sending `Content-Type: application/json` or authentication tokens. ```javascript
``` -------------------------------- ### trigger - JavaScript Example with Async Handling and shouldFocus Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform/trigger.mdx Demonstrates triggering validation in JavaScript with async/await pattern and optional shouldFocus parameter to focus inputs during error setting. Shows single field, multiple fields, and all fields validation. ```javascript import { useForm } from "react-hook-form" export default function App() { const { register, trigger, formState: { errors }, } = useForm() return (
) } ``` -------------------------------- ### Implement Basic Form Validation and Submission Source: https://github.com/react-hook-form/documentation/blob/master/src/content/get-started.mdx Demonstrates a basic form with input registration, validation for required fields, and submission handling using `useForm` and `handleSubmit`. ```tsx import { useForm, SubmitHandler } from "react-hook-form" type Inputs = { example: string exampleRequired: string } export default function App() { const { register, handleSubmit, watch, formState: { errors }, } = useForm() const onSubmit: SubmitHandler = (data) => console.log(data) console.log(watch("example")) // watch input value by passing the name of it return ( /* "handleSubmit" will validate your inputs before invoking "onSubmit" */
{/* register your input into the hook by invoking the "register" function */} {/* include validation with required or other standard HTML validation rules */} {/* errors will return when field validation fails */} {errors.exampleRequired && This field is required}
) } ``` ```javascript import { useForm } from "react-hook-form" export default function App() { const { register, handleSubmit, watch, formState: { errors }, } = useForm() const onSubmit = (data) => console.log(data) console.log(watch("example")) // watch input value by passing the name of it return ( /* "handleSubmit" will validate your inputs before invoking "onSubmit" */
{/* register your input into the hook by invoking the "register" function */} {/* include validation with required or other standard HTML validation rules */} {/* errors will return when field validation fails */} {errors.exampleRequired && This field is required}
) } ``` -------------------------------- ### Watching a Specific Field (JavaScript) Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/usewatch.mdx A JavaScript version of watching a specific field ('firstName') using useWatch. It demonstrates the same functionality as the TypeScript example but without type definitions. ```javascript import { useForm, useWatch } from "react-hook-form" function Child({ control }) { const firstName = useWatch({ control, name: "firstName", }) return

Watch: {firstName}

} function App() { const { register, control } = useForm({ defaultValues: { firstName: "test", }, }) return (
) } ``` -------------------------------- ### Reset a specific field with resetField Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform/resetfield.mdx This example demonstrates how to use `resetField` to reset a single form field, either keeping its dirty state or updating its default value. ```jsx onClick={() => resetField("firstName", { keepDirty: true })} > Reset keep dirty fields ) ``` -------------------------------- ### Initialize Form with Default Values Source: https://github.com/react-hook-form/documentation/blob/master/src/content/faqs.mdx Use the `defaultValues` option in `useForm` to set initial values for your form fields. This is the recommended approach for initializing forms. ```javascript function App() { const { register, handleSubmit } = useForm({ defaultValues: { firstName: "bill", lastName: "luo", }, }) return (
console.log(data))}>
) } ``` -------------------------------- ### Managing Input Unmounting with shouldUnregister Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform.mdx Demonstrates how to correctly handle input unmounting and notifications using `shouldUnregister: true`. It shows scenarios where direct unmounting doesn't trigger notifications and how `useWatch` or `useForm`'s useEffect can be used for proper handling. ```javascript const NotWork = () => { const [show, setShow] = React.useState(false) // ❌ won't get notified, need to invoke unregister return show && } const Work = ({ control }) => { const { show } = useWatch({ control }) // ✅ get notified at useEffect return show && } const App = () => { const [show, setShow] = React.useState(false) const { control } = useForm({ shouldUnregister: true }) return (
// ✅ get notified at useForm's useEffect {show && }
) } ``` -------------------------------- ### Zod Resolver Integration with React Hook Form Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform.mdx Integrate Zod validation schema with React Hook Form by passing the `zodResolver` to the `useForm` hook. Ensure Zod is installed. ```tsx import { useForm, } from "react-hook-form" import { zodResolver } from "@hookform/resolvers/zod" import * as z from "zod" const schema = z.object({ name: z.string(), age: z.number(), }) type Schema = z.infer const App = () => { const { register, handleSubmit } = useForm({ resolver: zodResolver(schema), }) return (
{ // handle inputs console.log(data) })} >
) } ``` -------------------------------- ### Yup Resolver Integration with React Hook Form Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform.mdx Integrate Yup validation schema with React Hook Form by passing the `yupResolver` to the `useForm` hook. Ensure Yup is installed. ```tsx import { useForm, } from "react-hook-form" import { yupResolver } from "@hookform/resolvers/yup" import * as yup from "yup" const schema = yup .object() .shape({ name: yup.string().required(), age: yup.number().required(), }) .required() const App = () => { const { register, handleSubmit } = useForm({ resolver: yupResolver(schema), // yup, joi and even your own. }) return (
console.log(d))}>
) } ``` -------------------------------- ### Registering Select and Input with Validation Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform/register.mdx Demonstrates how to register a select element and a text input with custom asynchronous validation using `register`. The validation checks product availability based on a selected category. ```javascript import { useForm } from "react-hook-form" import { checkProduct } from "./service" export default function App() { const { register, handleSubmit } = useForm() return (
{ if (!category) return "Choose a category" if (!product) return "Specify your product" const isInStock = await checkProduct(category, product) return isInStock || "There is no such product" }, }, })} />
) } ``` -------------------------------- ### trigger - TypeScript Example with Single, Multiple, and All Fields Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform/trigger.mdx Demonstrates triggering validation on a single field, multiple fields, and all fields using TypeScript. Shows how to use the trigger method with different parameter types (string, string[], and undefined). ```typescript import { useForm } from "react-hook-form" type FormInputs = { firstName: string lastName: string } export default function App() { const { register, trigger, formState: { errors }, } = useForm() return (
) } ``` -------------------------------- ### Prepend and Append with useFieldArray Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/usefieldarray.mdx Shows how to add new fields to the beginning (prepend) or end (append) of a field array. Includes options for focusing on specific fields after insertion. ```javascript import React from 'react'; import { useForm, useFieldArray } from 'react-hook-form'; const App = () => { const { register, control } = useForm({ defaultValues: { test: [{ value: '1' }, { value: '2' }], }, }); const { fields, prepend, append } = useFieldArray({ name: 'test', control, }); return (
{fields.map((field, i) => ( ))}
); }; ``` -------------------------------- ### Integrate React Hook Form with Redux Source: https://github.com/react-hook-form/documentation/blob/master/src/content/get-started.mdx This example demonstrates how to connect a React Hook Form component with a Redux store, allowing form data to be submitted to a Redux action. ```javascript import { useForm } from "react-hook-form" import { connect } from "react-redux" import updateAction from "./actions" export default function App(props) { const { register, handleSubmit, setValue } = useForm({ defaultValues: { firstName: "", lastName: "", }, }) // Submit your data into Redux store const onSubmit = (data) => props.updateAction(data) return (
) } // Connect your component with redux connect( ({ firstName, lastName }) => ({ firstName, lastName }), updateAction )(YourForm) ``` -------------------------------- ### Integrate useLens with React Hook Form (Object Return) Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/uselens.mdx Demonstrates integrating `useLens` with React Hook Form by calling `interop()` without arguments, returning an object with `control` and `name` for input registration. ```tsx const { control, name } = lens.interop() return ``` -------------------------------- ### Basic unregister usage with TypeScript Source: https://github.com/react-hook-form/documentation/blob/master/src/content/docs/useform/unregister.mdx Complete example showing how to use unregister to remove a field from the form. The lastName field is registered in useEffect and can be unregistered via button click. ```typescript import React, { useEffect } from "react" import { useForm } from "react-hook-form" interface IFormInputs { firstName: string lastName?: string } export default function App() { const { register, handleSubmit, unregister } = useForm() const onSubmit = (data: IFormInputs) => console.log(data) React.useEffect(() => { register("lastName") }, [register]) return (
) } ```