How to create a dynamic form using React JS

Introduction

React JS is a JavaScript library for building user interfaces. It lets you create reusable components so that your code is easy to read and maintain. When a user interacts with a React component, React updates the component automatically. This makes your app more responsive and fast.

React JS allows developers to create forms that change based on user input. This can be extremely useful for creating custom forms that are specific to a particular use case. Additionally, React JS helps to keep forms organized and easy to navigate.

In this tutorial, we will go through the steep so you understand how to do it in an easy way. Let’s get started with creating a simple form using React JS.

First of all, you may wonder what is a form! Let me put it simply this way- a form is an empty entity that might hold different values in it. It can be any type of value like name, age, address, email, number, etc. Here we’ll create a simple and static form that shows two rows.

import './App.css';
function App() {
  return (
    <div className="App">
      <form>
        <div>
          <input
            name='name'
            placeholder='Name'
          />
          <input
            name='salary'
            placeholder='Salary'
          />
        </div>
      </form>
    </div>
  );
}
export default App;

As you can see in the above example I have created two different input fields, which take “Name” and “Salary” values as inputs. However, the form is static. It can only accept the values, but can not do something with those values. The created form looks like this.

How to create a dynamic form using React JS

As you already know that the created above form is static. A static form is isolated and not pretty much useful. Our goal is to create a dynamic form. Let’s make the above form dynamic using React state management. To make the form dynamic I’ll create a React state, and this state will have an object that contains age and salary properties in it. Let’s do it.

const [inputFields, setInputFields] = useState([ \ {name: '', salary: ''} \ ]).

Here, the inputFields is a React state. Now, we can use this state to map our form fields. To use this state we must import the useState hook from the library.

import { useState } from 'react';
import './App.css';
function App() {
  const [inputFields, setInputFields] = useState([
    { name: '', salary: '' }
  ])
  return (
    <div className="App">
      <form>
        {inputFields.map((input, index) => {
          return (
            <div key={index}>
              <input
                name='name'
                placeholder='Name'
              />
              <input
                name='salary'
                placeholder='Salary'
              />
            </div>
          )
        })}
      </form>
    </div>
  );
}
export default App;

Boom! We are done. The above code will create a set of input fields with the properties “Name” and “Salary” since I’ve used one object in our state. We can increase the number of pairs anytime by adding more objects to the state.

Moreover, we can simply add the values from the inputFields state to the input fields by doing–

<input
    name='name'
    placeholder='Name'
    value={input.name}
/>

And the process is the same for the “Salary” property.

Let's imagine a real-time situation where we are in need of adding more fields to our form since our existing input fields are not sufficient. To solve the issue we may create a button named “Add More” that will create a new pair of input fields while clicking. Let’s make the button first.

<button>Add More</button>

Now we need a function that will work beneath this button. This function will trigger only when someone clicks the “Add More” button.

const addFields = () => {    
}

And now, let’s connect the function to our button by simply adding an onClick event.

&lt;button onClick={addFields}>Add More&lt;/button>.

So far so good! Our physical structure is ready. Now, we need to create a function that will create a new empty field every time we click the “Add More” button. Therefore, we need to make an object inside the addFields function, which will cause the result. This object will go back to the inputFields state while clicking and creating a new input field.

const addFields = () => {
    let newField = { name: '', salary: '' }
}

Now, we can put this newField object inside the inputFields state so that it can automate the process.

const addFields = () => {
    let newField = { name: '', salary: '' }

    setInputFields([...inputFields, newfield])
}

How to create a dynamic form using React JS

Note: The spread operator (three dots ) set up the new fields with existing values from the first input field.

Now, we can have more input fields by clicking the “Add More” button. Each click will add an extra pair of input fields with “Name” and “Salary” properties.

Next, we want to get another feature of a dynamic form, which is the “Submit” button. Let’s imagine a situation when we want to provide our information and send or submit it to the concerned person/company. In this scenario must have to have a submit button below our dynamic form. In this case, we need to create a “Submit” button like the previous one. Let’s get a “Submit

<button>Submit</button>

Then again, we need to have a function, which helps to get the button triggered when we click it. This function will save the data in the console, from the input fields. It also contains a method called e.preventDefault() that will prevent the page from getting refreshed. So that, the information becomes safe.

const submit = (e) => {
    e.preventDefault();
    console.log(inputFields)
}

Afterward, integrate this function with the “Submit” button so that it can send the data and log it in.

<button onClick={submit}>Submit</button>

Finally, add this to the form tag.

<form onSubmit={submit}>

When we submit the data using that “Submit” button we’ll have the below picture in our console log.

How to create a dynamic form using React JS

How to create a dynamic form using React JS

Lastly, we’ll add the “Remove” feature to our dynamic form. It becomes a pretty much useful feature when it comes to editing or removing the input field’s value of a form. By clicking the remove button we can erase the value of a row if we provide the wrong input mistakenly. Let’s add the remove feature to our form.

<button>Remove</button>

And now, we need a function that executes the operation. Let’s create the function and integrate it with the button.

<button onClick={() => removeFields(index)}>Remove</button>

The integration process..

const removeFields = (index) => { 
}

Finally, just like the previous button execution, we need to construct a new variable and store the inputFields state in that new variable.

const removeFields = (index) => {
    let data = [...inputFields];
}

How to create a dynamic form using React JS

We can remove our form data easily by slicing them by their index number. For instance, we have a table of four data pairs and we want to remove the first pair and save it to the console log.

How to create a dynamic form using React JS

Before slicing the form data

Now, I’m removing the data for Adam.

const removeFields = (index) => {
    let data = [...inputFields];
    data.splice(index, 0)
    setInputFields(data)
}

How to create a dynamic form using React JS

After slicing the form data

Now if we press the submit button we’ll have the updated data set in our console log.

Warming Up

Using React JS to create dynamic forms is a great way to improve the user experience on your website. It makes the form more responsive and easy to use, which can lead to more submissions. So if you're looking for a way to improve your forms, consider using React JS. It always provides an upper hand while making a dynamic form using React JS.