How to Handle Multiple Inputs in a React Form with the useState() Hook

Blendi Ibraj
2 min readJan 29, 2021

--

Hooks have simplified many aspects of coding in React. The biggest advantage is that we now have access to state and lifecycle method functionality in our functional components with the useState and useEffect Hooks, respectively.

After having used class components to build our forms in React, using the useState() Hook in order to dynamically control our inputs in a form can be tricky at first, so this is a guide on how to do just that. I’ll show you all of the code, then walk through it line-by-line.

First, it’s important to mention that useState() returns two things:

  1. The current state variable
  2. A function to update that state variable

So, we’ll declare these two things by “destructuring” them from the Hook, then setting our firstName and lastName state properties to empty strings (lines 2–4).

If we look at our form toward the bottom of the code, notice that we set our input values equal to the corresponding state properties (lines 18–19). Then, we set onChange equal to our callback, which we’ll define now.

We can now use our setField function within our handleChange callback to update our state according to what the user is typing into the form. Within our setField() invocation we use the spread operator in order to include the current state without modifying it (lines 8–9).

Then, using the event passed into the callback, we grab our name attribute from our form (which corresponds to the properties in our state) and set it equal to what the user is typing into the form (line 10). We have access to this user input from the value attribute, which we set equal to the appropriate state property.

And that’s it!

After using class components for so long, it can be quite difficult to transition to Hooks. However, with enough practice, you’ll thank yourself for learning Hooks, as they make your code cleaner and more readable.

Note: on line 10, we need to wrap e.target.name in square brackets so that we can dynamically update property. You can read more about computed property names here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names

--

--

Blendi Ibraj
Blendi Ibraj

Written by Blendi Ibraj

0 Followers

I'm a front-end developer based in NYC

No responses yet