React Hook Form is a powerful library for handling forms in React applications, including dynamic forms with varying form fields. In this blog post, we will explore how to use React Hook Form to create dynamic forms that adapt to user input.
Installation and Setup
Install React Hook Form in your project using npm or yarn:
npm install react-hook-form
Creating a Dynamic Form
- Create component
InputForm
and loop the componentInputForm
using array offields
fromuseFieldArray
. - Add Function
handleAddNew
to add newInputForm
when you click Add Button. useEffect
function to reset length of input form on the first load of a page.
import { type Control, Controller, type FieldValues, type RegisterOptions, useFieldArray, useForm } from "react-hook-form";
type InputFormProps = {
name: string,
placeholder: string,
control: Control<FieldValues> | undefined,
rules: Omit<RegisterOptions<FieldValues, string>, "valueAsNumber" | "valueAsDate" | "setValueAs" | "disabled"> | undefined
}
const InputForm: React.FC<InputFormProps> = ({ name, placeholder, control, rules }) => {
return <>
<div className="flex flex-col">
<Controller
render={({ field: { onChange }…