Two-way Data Binding in ReactJS – Part I

Simple Data Binding

What do Aurelia, VueJS, and Angular have in common? All three are modern frameworks that support two-way data binding. Of course, ReactJS famously omits this feature, and I believe the standard excuse runs along the lines of, “Flux is better.”

Except it isn’t.

Write enough change handlers, and you will eventually realize that what you are doing amounts to implementing your own version of two-way data binding. Why re-invent the wheel this way, when onChange and value — the two attributes we use to bind state to our forms — can be abstracted into a couple of simple methods? In today’s post we’ll explore how to do this.

Consider the following component:

In order to create this component, we had to write a (relatively) generic change handler, then repeat the work of attaching said change handler to each element that could trigger state changes, along with a value (or checked) attribute, and an argument representing the “key” of the state property to be updated on change. Our goal in Part I is to write a function that will eliminate all that work. It should have the following method signature:

We can use the return value to take advantage of the fact that JSX allows us to specify dynamic attributes, like this:

Each property on the object after the span [] represents an attribute that should be added to the JSX tag; so, the above is equivalent to:

What we need is a method that returns:

… for any property on the state object. To make this method reusable across components, we will return it as a function from a second method that accepts a component as its context:

But why add an identical copy of getChangeHandler(), to every component? Why not simply include it in our model binding instead?

Now we can get a reference to this method in our render() function:

… and call it to return a value/checked attribute and change handler for every element we want “bound” to our state:

Finally, change events may have additional side-effects, such as hiding or displaying buttons. In order to support this, our binder should call an optional, additional change handler after updating the component’s state:

And there you have it! A reusable method that can bind state properties to JSX elements. This is sufficient for simple state properties; however, what if state contains nested objects? For example, the method we used here will not work for a state object that looks like:

In Part II, we will investigate how to solve this problem with lodash.

The full source for the example used in this article is at https://github.com/abraham-serafino/react-data-binding/tree/Part-I.

One thought on “Two-way Data Binding in ReactJS – Part I

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*