Handling single/multiple input field(s) with a single onChange handler in React

Jay
3 min readAug 27, 2022

--

Form handling is one of the most important part of any system or software. Forms can have few input fields(like only “firstName” and “lastName”) in some cases and can also have many many input fields as per the system requirements.

Handling one or two input fields are easy. Just write states to track and re-render their values and onChange handler function for each of them to handle any change happening to the state effectively.

In above code, we have one input field and we are tracking it’s value using state, and handling the onchange behaviour using onChange handler function.

Now imagine, you have some 10–20 input fields like firstName, lastName, nickname, email, address, pincode and bla bla. Then what would you do??? Writing state for each input field and onChange handler for each of them individually??? That would make your code really nasty and 10–20 times more longer. It will be hard for other developers to maintain it also.

Then how?……here is one solution

Give a unique name attribute to each input field for react to dinstinguish between input fields. example .. name=”firstName”

Whenever any event happens like onChange, onClick, onSubmit etc. Then by default javascript gives us an event object which carry all the detailed information about the event that just happened. We can confirm from name field that which particular field is changing and store it’s value in state using dynamic key assignment.

the [event.target.name] notation denotes that the value inside in dynamic and will change.

Now to instead of writing multiple states for each input field we can just create a single state as an object and dynamically assign key(as shown above) and store the value(value produced after onChange) with it.

IMPORTANT: The name you assign in useState() as key should exactly match with the name attribute of input field. Like considering above state, the name attribute value of input fields should be exactly same as “firstName” and “lastName

Now we can write a single onChange handler function to handle states of every input field.

the three dots before state is a spread operator(…state), which copies the states as it is and adds the extra item.

A look at the complete code

complete code

SUMMARY → Whenever handling multiple user input fields(without any hooks) remember dynamic key allocation concept. Create single state with an object as initial state, a single onChange handler function that dynamically takes name attribute value as key and assign value to it. This makes life easier.

Thank you for reading 😊…

--

--

Jay

Tech enthusiast || Software Engineer || Right wing