React Hook Form- Create Dynamic Form Input Controls Example
In this tutorial, we will get to know how to create a dynamic form in React app. To create the custom dynamic form in the React functional component, we will be using React Hooks, React Hook Form, Yup, Bootstrap Packages, Module Libraries.
The form is the gap between us and our site visitors and opens the doorway to many opportunities in our React journey.
Being a React developer, in the majority of our time, we deal with forms. Forms are made using form controls such as text, password fields, checkboxes, radio buttons, sliders, labels, action buttons, etc.
In general, forms are static components with some pre-defined input controls laid down on a web page. Almost all of us, know a thing or two about forms.
Let’s now learn in detail:
How to Build Dynamic Input Fields In React With Hook Form.
Step 1- Set Up New Application
Step 2- Install Bootstrap Plugin
Step 3- Add Yup And Hook Form Plugins
Step 4- Build Form Component
Step 5- Register New Component In App Js
Step 6- Start React Server
Step 1- Set Up New Application
As we know that our very first step is just to install or download the new blank React app using create-react-app:
npx create-react-app react-space
Further, we get into the app root:
cd react-space
Step 2- Install Bootstrap Plugin
Next is required to use the following command to install Bootstrap framework in React:
npm install bootstrap
Afterward, we need to get into the App.js file. Then, we define at the top part the bootstrap’s CSS path:
import 'bootstrap/dist/css/bootstrap.min.css'
Step 3- Add Yup And Hook Form Plugins
In the third step, we will have to add Yup and Hook Form Plugins together. The below-given command will be used for installing both the packages:
npm install @hookform/resolvers yup
Step 4- Build Form Component
Now, we have to get to the main point i.e. the components/ folder. Then, we make the DynamicForm.js file. In this file, we will be using the below code:
import React, { useEffect } from 'react'
import { yupResolver } from '@hookform/resolvers/yup'
import * as Yup from 'yup'
import { useForm, useFieldArray } from 'react-hook-form'
function BasicForm() {
const JsSchema = Yup.object().shape({
FavFood: Yup.string().required('Value is mendatory!'),
food: Yup.array().of(
Yup.object().shape({
name: Yup.string().required('Value is mendatory'),
}),
),
})
const optionsDf = { resolver: yupResolver(JsSchema) }
const {
control,
formState,
handleSubmit,
register,
watch,
reset,
} = useForm(optionsDf)
const { errors } = formState
const { fields, append, remove } = useFieldArray({ name: 'food', control })
const FavFood = watch('FavFood')
useEffect(() => {
const currentProp = parseInt(FavFood || 0)
const previousProp = fields.length
if (currentProp > previousProp) {
for (let i = previousProp; i < currentProp; i++) {
append({ name: '' })
}
} else {
for (let i = previousProp; i > currentProp; i--) {
remove(i - 1)
}
}
}, [FavFood])
function onSubmit(res) {
console.log(JSON.stringify(res, null, 4))
}
return (
<div className="container mt-5">
<form onSubmit={handleSubmit(onSubmit)}>
<h2 className="mb-3">React Hook Dynamic Form Tutorial</h2>
<div className="form-group">
<label className="mb-2">What is your fav food?</label>
<select
name="FavFood"
{...register('FavFood')}
className={`form-control ${errors.FavFood ? 'is-invalid' : ''}`}
>
{['Select Options', 1, 2, 3, 4, 5, 6].map((i) => (
<option key={i} value={i}>
{i}
</option>
))}
</select>
<div className="invalid-feedback">{errors.FavFood?.message}</div>
</div>
{fields.map((item, i) => (
<div key={i} className="mt-3 mb-2">
<div>
<strong className="text-primary">food {i + 1}</strong>
<div className="form-group">
<input
name={`food[${i}]name`}
{...register(`food.${i}.name`)}
className={`form-control ${
errors.food?.[i]?.name ? 'is-invalid' : ''
}`}
type="text"
/>
<div className="invalid-feedback">
{errors.food?.[i]?.name?.message}
</div>
</div>
</div>
</div>
))}
<button type="submit" className="btn btn-success mt-3 mb-2">
Submit
</button>
<button
onClick={() => reset()}
type="button"
className="btn btn-info">
Reset
</button>
</form>
</div>
)
}
export default BasicForm
Step 5- Register New Component In App Js
So, in this step, we will head over to App.js file and import as well as register the BasicForm component:
import React from 'react'
import BasicForm from './components/BasicForm'
import 'bootstrap/dist/css/bootstrap.min.css';
export default function App() {
return (
<div className="App">
<BasicForm />
</div>
)
}
Step 6- Start React Server
Now, we have to start the React server since we have reached the last state of this tutorial.
It would be done when we use the following command to run the application:
npm start
Conclusion
So, Dynamic Forms are handy and provide unbound freedom since we can easily change the form values in real-time. We can also add many input controls as per our requirement.
Dynamic Forms play a significant role at that time when we have to enter the values which are not sure in number.
In this guide, we have seen how to build dynamic forms in a React app. Hope that you found the steps quite easy and swift to follow to execute.
Good luck!