Building dynamic forms in React can be a powerful way to create user-friendly interfaces for collecting data. In this post, we’ll explore how to build a dynamic form that can add and remove form fields on the fly, using the popular React library and arrow function for handling events.

A step by step guide on how to build a dynamic form in React

Step 1. use useState hook

Start by setting up a basic React component that renders a form. Use the useState hook to create a state object that holds the form fields and their values.

import React, { useState } from 'react';

function App() {
  const [formFields, setFormFields] = useState([
    { type: '', value: '' }
  ]);

Step 2. Functions for dynamic forms

Create arrow functions for handling the onChange, addField, and removeField events. The handleChange function should take the event object and the index of the field being changed as arguments, and use them to update the corresponding field in the state. The addField function should simply add a new field to the state, and the removeField function should remove the field at the specified index from the state.

  const handleChange = (event, index) => {
    let data = [...formFields];
    data[index][event.target.name] = event.target.value;
    setFormFields(data);
  }

  const addField = () => {
    let object = { type: '', value: '' }
    setFormFields([...formFields, object])
  }

  const removeField = (index) => {
    const updatedFields = [...formFields];
    updatedFields.splice(index, 1);
    setFormFields(updatedFields);
  }
  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log(formFields)
  }

Step 3. Add form

In the return statement, map over the formFields array to render an input field for each item in the array.

  return (
    <form>
      {formFields.map((field, index) => (
        <div key={index}>
          

Read other Techtalksick tutorials – here

Step 4. Add fields

For each input field, set the value attribute to the corresponding value from the formFields array and the onChange attribute to the handleChange function.

            <input
            type="text"
            name="type"
            placeholder="Type Type"
            style={{ margin: "5px" }}
            onChange={event => handleChange(event, index)}
            value={field.type}
          />
          <input
            type="text"
            name="value"
            placeholder="Type value"
            style={{ margin: "5px" }}
            onChange={event => handleChange(event, index)}
            value={field.value}
          />

Step 5. Add buttons for add fields and remove fields

Also add a button next to each form field that, when clicked, removes the corresponding field from the state. Add a button at the bottom of the form that, when clicked, adds a new field to the state.

<button type="button" onClick={() => removeField(index)}>Remove</button>
        </div>
      ))}
      <button type="button" onClick={addField}>Add Field</button>
      <hr />
      <button type="submit">Submit</button>
    </form>
  );
}

export default App;

Output:

If we run our react app we will see this basic form

Basic Dynamic Forms
Basic Dynamic Forms

Form with input data, add field and remove buttons are working fine. And if we submit, we will see our updated data in the console.

Handle dynamic Multiple fields in react
Handle dynamic Multiple fields in react

Full code in one view:

import React, { useState } from 'react';

function App() {
  const [formFields, setFormFields] = useState([
    { type: '', value: '' }
  ]);

  const handleChange = (event, index) => {
    let data = [...formFields];
    data[index][event.target.name] = event.target.value;
    setFormFields(data);
  }

  const addField = () => {
    let object = { type: '', value: '' }
    setFormFields([...formFields, object])
  }

  const removeField = (index) => {
    const updatedFields = [...formFields];
    updatedFields.splice(index, 1);
    setFormFields(updatedFields);
  }
  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log(formFields)
  }

  return (
    <form onSubmit={handleSubmit}>
      <h3>Dynamic Forms in React</h3>
      {formFields.map((field, index) => (
        <div key={index} style={{ marginBottom: "10px" }}>
          <input
            type="text"
            name="type"
            placeholder="Type Type"
            style={{ margin: "10px" }}
            onChange={event => handleChange(event, index)}
            value={field.type}
          />
          <input
            type="text"
            name="value"
            placeholder="Type value"
            style={{ margin: "10px" }}
            onChange={event => handleChange(event, index)}
            value={field.value}
          />
          <button type="button" onClick={() => removeField(index)}>Remove</button>
        </div>
      ))}
      <button type="button" onClick={addField}>Add Field</button>
      <hr />
      <button type="submit">Submit</button>
    </form>
  );
}

export default App;

In this code, we have a form that renders an input field for each item in the formFields array. The input fields are populated with the corresponding label and value from the array. The onChange event is handled by the handleChange function which takes the event object and the index of the field being changed as arguments, and uses them to update the corresponding field in the state. The addField function simply adds a new field to the state, and the removeField function removes the field at the specified index from the state.

This makes the code more readable and maintainable. It also allows to reuse the same function in other places, which is a good practice.

With this approach, you can easily add or remove fields from your form, making it dynamic and user-friendly. You can expand on this concept by adding more advanced form fields, such as checkboxes and radio buttons, and by implementing form validation.

This is a basic example of how to build a dynamic form in React using arrow functions. The knowledge of this example will help you to create more functionality to your forms and make it more user-friendly.

Try out the code here – https://github.com/muarju/dynamic-forms-react

Categorized in: