In this tutorial, we will show you how to create a dynamic form in React app. To create the custom dynamic form in the React functional component, we will use React hooks, React hook form, yup, Bootstrap packages, and module libraries.
The form is the gap between you and your site visitors and opens the doorway to many opportunities in our React journey.
As a React developer, in the majority of our time, we deal with forms. Forms are made using form controls, such as text fields, 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.
Although, creating static form is as easy as pie. However, do you know how to create a dynamic form in React?
No worries, if you don’t know.
Let’s straight go to your favorite code editor and start writing some code.
Let us first start with installing the new blank React application, this will be the place where the dynamic form will be developed.
npx create-react-app react-space
Next, get into the app’s root.
cd react-space
Next, we move one step further and use command to install bootstrap framework in React.
npm install bootstrap
Further, get into the App.js file, define at the top part the bootstrap’s CSS path.
import 'bootstrap/dist/css/bootstrap.min.css'
In this step, we will add yup and hook form plugins together. The below-mentioned command can be used to install both packages together.
npm install @hookform/resolvers yup
Let’s get to the main point, as per the common notion get into the components/ folder, then make the DynamicForm.js file. In this file, you have to lay down all the following 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
Eventually, we need to head over to App.js file and import and 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>
)
}
We are about to test the dynamic form, to do that you make sure to start the React server.
It can be done, via given command. Execute the command to run the application.
npm start
Here is the URL, paste and press enter to view the form module on the browser.
http://localhost:3000
Dynamic forms are handy and provide unbound freedom why because you can change the form values in real-time. You can add several input controls based on your requirement.
Seldom are there situations where you have to enter the values which are not sure in numbers. At this time, dynamic forms come into play.
Through the help of this guide we suggested some simple steps to build dynamic form in React. We tried to solve complex methods in more simple steps and shed light on every bit.
Which is significant and will surely help you create a dynamic form component in React.
In this post, we will learn how to work with HTTP requests in the Redux…
MySQL is a relational database management system based on SQL – Structured Query Language, and…
React Js Handle Rest API data globally with Context and useState hook tutorial. In this…
Node js delete data from MySQL database tutorial; Throughout this guide, you will ascertain how…
In this tutorial, you will discover how to import CSV file into MySQL database using…
React Js Global state management with createContext hook example; In this tutorial, we will help…