How to Build Dynamic Forms in React

Forms are a fundamental part of web applications, and React makes it easy to create dynamic and interactive forms. In this tutorial, we’ll explore how to build dynamic forms in React using the useState hook. Specifically, we’ll create a form where users can dynamically add and remove input fields.

Setting Up the Project

Before we start, make sure you have a React project set up. You can create a new project using Create React App or use an existing one.

npx create-react-app dynamic-forms
cd dynamic-forms
npm start

Creating the DynamicForm Component

Let’s create a new component called DynamicForm.js. This component will manage our dynamic form.

// DynamicForm.js
import React, { useState } from 'react';

const DynamicForm = () => {
  // State to manage the dynamic fields
  const [fields, setFields] = useState([{ name: '', value: '' }]);

  // Function to add a new input field
  const addField = () => {
    setFields([...fields, { name: '', value: '' }]);
  };

  // Function to handle changes in input fields
  const handleFieldChange = (index, field, property, value) => {
    const updatedFields = [...fields];
    updatedFields[index] = { ...field, [property]: value };
    setFields(updatedFields);
  };

  // Function to remove a field by index
  const removeField = (index) => {
    const updatedFields = [...fields];
    updatedFields.splice(index, 1);
    setFields(updatedFields);
  };

  // Render the dynamic form
  return (
    <div>
      <h2>Dynamic Form</h2>
      <form>
        {fields.map((field, index) => (
          <div key={index}>
            <input
              type="text"
              placeholder="Name"
              value={field.name}
              onChange={(e) => handleFieldChange(index, field, 'name', e.target.value)}
            />
            <input
              type="text"
              placeholder="Value"
              value={field.value}
              onChange={(e) => handleFieldChange(index, field, 'value', e.target.value)}
            />
            <button type="button" onClick={() => removeField(index)}>
              Remove
            </button>
          </div>
        ))}
      </form>
      <button type="button" onClick={addField}>
        Add Field
      </button>
      <div>
        <h3>Form Data:</h3>
        <pre>{JSON.stringify(fields, null, 2)}</pre>
      </div>
    </div>
  );
};

export default DynamicForm;

Explaining the Code

1. State Initialization

const [fields, setFields] = useState([{ name: '', value: '' }]);

We use the useState hook to initialize the state fields, representing the dynamic input fields. The initial state contains an object with name and value properties.

2. Adding Fields (addField function)

const addField = () => {
  setFields([...fields, { name: '', value: '' }]);
};

The addField function is called when the user clicks the “Add Field” button. It adds a new input field to the existing array of fields.

3. Handling Field Changes (handleFieldChange function)

const handleFieldChange = (index, field, property, value) => {
  const updatedFields = [...fields];
  updatedFields[index] = { ...field, [property]: value };
  setFields(updatedFields);
};

The handleFieldChange function is called when any input field changes. It updates the corresponding field in the state array with the new value.

4. Removing Fields (removeField function)

const removeField = (index) => {
  const updatedFields = [...fields];
  updatedFields.splice(index, 1);
  setFields(updatedFields);
};

The removeField function removes a field based on its index in the array.

5. Rendering Input Fields

{fields.map((field, index) => (
  <div key={index}>
    <input
      type="text"
      placeholder="Name"
      value={field.name}
      onChange={(e) => handleFieldChange(index, field, 'name', e.target.value)}
    />
    <input
      type="text"
      placeholder="Value"
      value={field.value}
      onChange={(e) => handleFieldChange(index, field, 'value', e.target.value)}
    />
    <button type="button" onClick={() => removeField(index)}>
      Remove
    </button>
  </div>
))}

We use the map function to render input fields dynamically based on the current state. Each field has input elements for “Name” and “Value” and a “Remove” button.

6. Form Data Display

<div>
  <h3>Form Data:</h3>
  <pre>{JSON.stringify(fields, null, 2)}</pre>
</div>

The form data is displayed below the form for visualization purposes. The JSON.stringify function is used to format the JSON data.

Using the DynamicForm Component

Now, let’s use the DynamicForm component in our main App.js file.

// App.js
import React from 'react';
import DynamicForm from './DynamicForm';

function App() {
  return (
    <div className="App">
      <DynamicForm />
    </div>
  );
}

export default App;

Running the Application

Save your changes and run your React application.

npm start

Visit http://localhost:3000 in your browser. You should see the “Dynamic Form” with the ability to add, remove, and edit input fields dynamically.

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru