How to Create Dynamic Input Fields in React 18

Last Updated on by in React JS

In websites or web pages, dynamic input fields are essential, and allow users to enter and send data to servers freely with no limited restriction at all.

In this comprehensive guide, we’ll learn how to create dynamic input fields using React functional component, useReducer hook, and React v18 forms.

The useReducer hook in React is a powerful tool primarily used for state management within functional components. It’s beneficial for handling complex state logic or scenarios where state transitions follow particular patterns.

We’ll use the useReducer hook to extend the capability of form input controls in React, bye the end of this guide, you will understand how useReducer hook serve the prime purpose in organizing and regulating the input control behavior.

Static forms are adequate for limited amount of data, but dynamic forms give users the ability to smoothly add more input controls that grants the to submit additional information.

Let’s explore the below process to know utterly how to build dynamic input fields using React components and hooks.

Step 1: 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

Step 2: 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 --legacy-peer-deps

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';

Step 3: Create Dynamic Forms in React Function Component

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

Step 4: 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

Step 5: 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

Dynamic input fields in React open up a world of possibilities for improving data processing and user interactions in applications.

Based on user requirements or increasing data needs, web developers can effectively build dynamic input fields functionality by utilizing React’s functional component structure and hooks.

React’s flexibility enables the development for the generation of multiple input fields that can handle a wide range of data from a simple form.