React Quick Tip: Easy Data Binding with a Generic `onChange` Handler

dave.js
Frontend Weekly
Published in
2 min readJan 30, 2018

--

As a beginner with React, I found myself creating many, very similar, onChange handlers for text fields in order to achieve data binding using state. I would often look something like this:

onFieldNameChange = (e) => {
this.setState({ firstName: e.target.value });
}
onLastNameChange = (e) => {
this.setState({ lastName: e.target.value });
}
/* continue for every text field... */

But what I noticed about these handlers was that I was often writing the exact same code, with only a different field name for updating state.

So I began to wonder: Is it possible to write only one generic onChange handler to use for all text fields?

The answer: Yes!

In the snippet above, we use e.target.value to get the new value of the text fields in order to update state, but we can also use target get other useful data. In this example, we also access name from the e.target and use it as a key when calling this.setState in our onChange handler:

class Form extends Component {
state = {
firstName: '',
lastName: '',
/* Initialize all text fields with empty strings. */
}
onChange = e => this.setState({ [e.target.name]: e.target.value }) render() {
const {
firstName,
lastName,
/* Destructure other fields... */
} = this.state;
return (
<form>
<input
type="text"
name="firstName"
value={firstName}
onChange={this.onChange}

/>
<input
type="text"
name="lastName"
value={lastName}
onChange={this.onChange}

/>
/* Render other fields... */
</form>
);
}
}

Now we can add a new text field and easily add data binding without having to write a new onChange hander. It’s that simple!

When to Not Use a Generic onChange Handler

As with everything in programming, there are always tradeoffs. A generic onChange handler is great when you just need to update state whenever the text field value changes, but it becomes less suitable when more functionality is needed for specific fields.

For example, if you need to validate the format of an email address, or check the strength of a password, custom handlers for those fields might be a more suitable solution.

Always weigh the pros and cons and choose the approach that works best in each specific case.

--

--

dave.js
Frontend Weekly

I’m an artsy software engineer. I write about JavaScript/React, and sometimes my opinions about other things. ¯\_(ツ)_/¯