Handle Multiple Inputs in React with ES6 Computed Property Name

Zac Jones
3 min readOct 22, 2017

--

create-react-app (CRA) was used to generate the necessary boilerplate to start this React application. If you haven’t used it before, you should! There is zero configuration and you won’t need to touch Webpack or Babel. 😄

Here’s a great tutorial on CRA if you haven’t heard about it before: Bootstrap a React Application through the CLI with Create React App

Controlled Input

The standard way React handles user input is through Controlled Inputs. The React component that renders the form defines a function that determines what we do with user input in that form.

Controlled Input

In the above example, user input is being handled by the functionhandleChange which sets the components state variable, userInput, to the string typed by the user. userInput is then set as the value of the input.

The resulting output is rendered to the screen for feedback.

Output

The Problem of scaling Controlled Inputs

The problem that we run into is when we want to add more and more input fields into our Component is that it becomes needlessly verbose. The intuitive way to add more inputs (at-least for me) is to just keep adding functions to handle the extra inputs.

It works

Each input has it’s own ‘handleChange’ function which works but we broke one of the biggest rules in software development, DRY.

Don’t Repeat Yourself! We just did that 2 times. 😳

Other than the state variables being updated, these functions are the same. There has to be a better way to do this.

ES6 Computed Property Name

ES6 Computed Property Name’s solve this exact problem for us. We can set a name property on each input and access that property dynamically by using the bracket [] syntax of Computed Property Names.

Note that the name is the same as the value it is updating
Works again!

We now have all our inputs handled by a single function that will take in the name of the input and update the corresponding state value.

We can even clean up our handleChange function by using a little more destructuring.

--

--