Dynamic React forms

March 15, 2021

Forms of some kind are imperative in web development.

At one point or another you’re going to need to ask for input from the user and forms are the go to way to capture user input.

But if our application’s input requirements are not fixed, we may also need to let the user add/remove inputs fields accordingly.

For Example if we need a form where a user can add the names of the pets he has in separate text input boxes, we can allow the user to add new text boxes for as many number of pet names respectively.

Here we’ll discuss how can we do exactly that in React.

First let’s start with creating a simple form in react

function DynamicForms() {
  return (
    <div>
      <form
        style={{
          width: `200px`,
          display: `flex`,
          flexDirection: `column`
        }}
      >
        <input type="text" placeholder="Static input field" />
      </form>
    </div>
  );
}

We’ll add a button to add input fields:

function DynamicForms() {
  const addField = function(e) {
    e.preventDefault();
  };

  return (
    <div>
      <form
        style={{
          width: `200px`,
          display: `flex`,
          flexDirection: `column`
        }}
      >
        <input type="text" placeholder="Static input field" />
        <button onClick={addField}>Add Field</button>
      </form>
    </div>
  );
}

Now let’s create a state in our component which will match our number of input fields.

function DynamicForms() {
  const [formState, setFormState] = React.useState([]);

  const addField = function(e) {
    e.preventDefault();
  };
  return (
    <div>
      <form
        style={{
          width: `200px`,
          display: `flex`,
          flexDirection: `column`
        }}
      >
        <input type="text" placeholder="Static input field" />
        {formState.map(e => (
          <input type="text" placeholder={e.placeholder} />
        ))}
        <button onClick={addField}>Add Field</button>
      </form>
    </div>
  );
}

Adding new input fields on button click:

We just have to increment our formState object and the component will create the new input fields according to the updated state.

function DynamicForms() {
  const [formState, setFormState] = React.useState([]);

  const addField = function(e) {
    e.preventDefault();
    setFormState([
      ...formState,
      { placeholder: formState.length + 1 + " dynamic field" }
    ]);
  };
  return (
    <div>
      <form
        style={{
          width: `200px`,
          display: `flex`,
          flexDirection: `column`
        }}
      >
        <input type="text" placeholder="Static input field" />
        {formState.map(e => (
          <input type="text" placeholder={e.placeholder} />
        ))}
        <button onClick={addField}>Add Field</button>
      </form>
    </div>
  );
}

Written by Gagandeep Rangi who likes to talk about himself in third person. Twitter Instagram