DEV Community

Awais Abbas
Awais Abbas

Posted on

Creating Dynamic form in React

In a React app, you have a form with several input fields, and you want to allow users to dynamically add or remove fields on the form.

To implement this use case, you can create a state object in your React component that stores an array of input values.

function DynamicForm() {
  const [inputValues, setInputValues] = useState(['']);

  return (<></>)
}
Enter fullscreen mode Exit fullscreen mode

When the user clicks a button to add a new field, you can update the state object to include a new empty value. Similarly, when the user clicks a button to remove a field, you can update the state object to remove the corresponding value.

  function handleAddField() {
    setInputValues([...inputValues, '']);
  }

  function handleRemoveField(index) {
    const newInputValues = [...inputValues];
    newInputValues.splice(index, 1);
    setInputValues(newInputValues);
  }

  function handleChangeField(index, value) {
    const newInputValues = [...inputValues];
    newInputValues[index] = value;
    setInputValues(newInputValues);
  }

  function handleSubmit(event) {
    event.preventDefault();
    // do something with inputValues
  }
Enter fullscreen mode Exit fullscreen mode

To render the form fields dynamically, you can use the map() function to iterate over the array of input values and create a new input element for each value. You can also add a unique key to each input element to help React efficiently update the DOM when the state changes.

Here is how the component looks finally:

import React, { useState } from 'react';

function DynamicForm() {
  const [inputValues, setInputValues] = useState(['']);

  function handleAddField() {
    setInputValues([...inputValues, '']);
  }

  function handleRemoveField(index) {
    const newInputValues = [...inputValues];
    newInputValues.splice(index, 1);
    setInputValues(newInputValues);
  }

  function handleChangeField(index, value) {
    const newInputValues = [...inputValues];
    newInputValues[index] = value;
    setInputValues(newInputValues);
  }

  function handleSubmit(event) {
    event.preventDefault();
    // do something with inputValues
  }

  return (
    <form onSubmit={handleSubmit}>
      {inputValues.map((value, index) => (
        <div key={index}>
          <input
            type="text"
            value={value}
            onChange={(event) => handleChangeField(index, event.target.value)}
          />
          <button type="button" onClick={() => handleRemoveField(index)}>
            Remove
          </button>
        </div>
      ))}
      <button type="button" onClick={handleAddField}>
        Add Field
      </button>
      <button type="submit">Submit</button>
    </form>
  );
}

Enter fullscreen mode Exit fullscreen mode

In this example, the state object inputValues is an array of strings, each representing the value of an input field. The handleAddField() function adds a new empty string to the array, the handleRemoveField() function removes a string at a given index, and the handleChangeField() function updates a string at a given index.

The form fields are rendered dynamically using the map() function, with each input element having a unique key based on its index in the array. The handleSubmit() function is called when the user submits the form, and it can access the current inputValues array to do something with the user input.

With this solution, users can dynamically add or remove fields on a form in a React app, making it more flexible and user-friendly.

Top comments (0)