React Tutorials

React Hook Form Create Dynamic Form Input Controls Tutorial

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.

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

Set Up New Application

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

Install Bootstrap Plugin

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'

Add Yup and Hook Form Plugins

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

Build Form Component

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

Register New Component in App js

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>
  )
}

Start React Server

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

Conclusion

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.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.

Recent Posts

React Redux Handle API Calls with Thunk Middleware Tutorial

In this post, we will learn how to work with HTTP requests in the Redux…

1 day ago

Node AJAX Retrieve Records from MySQL Database Tutorial

MySQL is a relational database management system based on SQL – Structured Query Language, and…

4 days ago

React Manage REST API State Globally with Context API Tutorial

React Js Handle Rest API data globally with Context and useState hook tutorial. In this…

1 week ago

How to Delete Data from MySQL Database using Node Js

Node js delete data from MySQL database tutorial; Throughout this guide, you will ascertain how…

1 week ago

Node Import CSV File Data to MySQL Database with HTML Form

In this tutorial, you will discover how to import CSV file into MySQL database using…

2 weeks ago

How to Handle Global State in React js using Context API

React Js Global state management with createContext hook example; In this tutorial, we will help…

2 weeks ago