How to Build Dynamic Form in React Js using React Hooks

Last updated on: by Digamber

React form tutorial; Forms help extract valuable information from the user and make the client communication process facile.

You are into React development domain and don’t know how to build dynamic forms in React.

In general, a webform is laid down on a web page. It enables a user to enter data sent to a server for processing.

This guide will show you the right path towards form building. In this tutorial, we will show you how to build a form in React using React hook.

To build the form component in React, we will introduce you to the useReducer hook that will make the form creation process uncomplicated.

The useReducer hook is used in React functional component. This hook is generally used to manage the multiple and complex states in the React stateless component.

Create React Form Component with useReducer React Hook Example

  • Step 1: Generate React Project
  • Step 2: Add Bootstrap Library
  • Step 3: Make Form with useReducer
  • Step 4: Add Component in App
  • Step 5: Start Development Server

Generate React Project

Let us invoke the following command to manifest the new blank react project on our development system.

npx create-react-app cool-form

Don’t forget to step inside the project.

cd cool-form

Add Bootstrap Library

Bootstrap accommodates the time we might waste in building the user-friendly user interface components.

You may use the suggested command to add the bootstrap package.

npm install bootstrap

However it needs to be injected in the App.js file that makes it available globally in the react app.

import 'bootstrap/dist/css/bootstrap.min.css';

Make Form with useReducer

We are creating a basic form with only name, email, and password value. What we are trying to do here is to update the form state every time a user types a new value into the input fields.

For making such a feature, we are taking the help of the useReducer hook, which is exactly doing what is expected.

So, head over to components/BasicForm.js file and add the given code.

import React, { useReducer } from 'react'
export default function BasicForm() {
  const initForm = {
    name: '',
    email: '',
    password: '',
  }
  const [formVal, dispatch] = useReducer(
    (curVal, newVal) => ({ ...curVal, ...newVal }),
    initForm,
  )
  const { name, email, password } = formVal
  const onValChange = (event) => {
    const { name, value } = event.target
    dispatch({ [name]: value })
    console.log(formVal)
  }
  const onSubmit = (e) => {
    e.preventDefault()
    console.log(formVal)
  }
  return (
    <div>
      <form onSubmit={onSubmit} noValidate>
        <div className="form-group mb-2">
          <label className="mb-2">
            <strong>Name</strong>
          </label>
          <input
            required
            type="text"
            name="name"
            value={name}
            className="form-control"
            onChange={onValChange}
          />
        </div>
        <div className="form-group mb-2">
          <label className="mb-2">
            <strong>Email</strong>
          </label>
          <input
            type="text"
            name="email"
            value={email}
            className="form-control"
            onChange={onValChange}
          />
        </div>
        <div className="form-group mb-2">
          <label className="mb-2">
            <strong>Password</strong>
          </label>
          <input
            type="text"
            name="password"
            value={password}
            className="form-control"
            onChange={onValChange}
          />
        </div>
        <div>
          <button type="submit" className="btn btn-primary">
            Create
          </button>
        </div>
      </form>
    </div>
  )
}

Add Component in App

If you want to show the simple form on the browser, you make sure that you have imported and register the basic form in the App.js component.

import React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css';
import BasicForm from './components/BasicForm'
function App() {
  return (
    <div className="container mt-2">
      <BasicForm />
    </div>
  )
}
export default App

Start Development Server

Again, on your code editor’s command line tool, you have to type the command and invoke the react application.

npm start

How to Build Dynamic Form in React Js using React Hooks

Conclusion

You may undoubtedly call it an alternative to useState, and this hook takes a reducer (type(state, action) => newState) simultaneously returns a new form typically bound with the dispatch method.

When we first used the useReducer hook, we were skeptical about it, gradually we became used to it, and our outlook utterly changed.

In this tutorial, we have learned how to make a form and manage the state of React form using the useReducer hook.

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.