Open In App

How to handle multiple input field in react form with a single function?

There are two types of form, one is uncontrolled form and another one is controlled form. In uncontrolled form values of the input field stored in DOM and whenever we want to use the values we have to reach the DOM and pull out the values of each input field. Now in control, we do not allow to store the value in DOM but values are store as a state of react component and updated dynamically with user interaction. For this, we use the event handler onChange and executes a callback that updates the state values.  Now for a single input field, we use one handleChange callback but if the input fields are multiple then we have to create multiple handleChange callbacks to update the state of each input field. Fortunately, this is not the case. JavaScript provides us with ES2015 modern syntax to execute this kind of complicated work in a simple manner.

ES2015 introduced the ability to create objects with dynamic keys based on JavaScript expression called as computed property names. We use computed property names to update the state of all the input fields based on the name attribute of inputs. 



Syntax : 

const obj = {
   : value
}

Example 1: This example shows how to handle multiple form input fields with a single handleChange function.



Output :

Example 2 : 

Output :


Article Tags :