Repetition, repetition, repetition, using Computed Property Names to update React State

You come across tidbits of code that pop up from time to time. In React there is the concept of a single source of truth when it comes to state — this ends up being a problem when you have a form field in which you want to update state, and then even a bigger problem when it comes to update multiple fields and bind each of their values to unique state properties.

Last year I would frequently have a series of functions like this:


handleNameChange = event => {
this.setState({
name: event.target.value
})
}

handleDateChange = event => {
this.setState({
date: event.target.value
})
}

 

Each of the above functions changing a unique state property and then on each individual html input I would call each function onChange

After watching some development resources I saw someone code the above in a more reusable fashion.


handleChange = event => {
const { name, type, value } = event.target;
const val = type === "number" ? parseFloat(value) : value;
this.setState({
[name]: val
});
};

Creating a reusable function that works across all inputs within a form that follow the same pattern. Kinda cool!

I’ve seen the pattern before, but I didn’t have the terminology to actually explain it — I found that the technique that is applied to [name] above is actually called Computed Property Names. Doing a little bit more digging I found some videos by Tyler McGinnis and even a similar article to the one I’m writing now on Medium!

About the Author

Headshot of Mathias Rechtzigel with some sweet lazers in the background. Like the type you would find in a cheesy Sears photoshoot. Yeah those ones.

Mathias Rechtzigel is a web creator, his skills range from development, design, user experience and sometimes content creation.

He lives in Minneapolis, Minnesota with his partner (Ellen), dog (Bard), and two cats ( Pippi & Misti ).

Connect with me on

Join me on my journey

Sign up and I'll send you a weekly email with links to my posts, and other valuable links that I find througout the week.