Two-way Data Binding in ReactJS – Part III

Variable-length Arrays

In Part I, we learned how to automatically bind top-level state properties to form elements in JSX, so that updates to those elements automatically updated state and vice versa.

In Part II, we solved for nested objects and properties within our state object by incorporating lodash into our data binding library.

Now, in Part III, we’ll look at a somewhat harder two-way data binding problem: variable-length arrays.

You’ve probably already guessed that the guest1 and guest2 state properties from Part II are less than ideal; if possible, we’d like an array to which we can add guests, and which can also be empty. Something like this:

In theory, we could then add guests to the array with a method like this one:

… and render the array with a function like this one:

So what’s wrong here? Sure, guests[0].name will return the first guest from our state’s guests array the first time, but our model() function will replace the entire array with a single-element array containing only the updated value.

In other words, imagine we are in a browser’s Javascript console when the debugger is stopped on a breakpoint, and watch what happens:

As you can see, the entirety of myArray was replaced with a new array containing only a single element! Although not immediately obvious from renderGuests()‘ JSX, this result makes sense when we observe it in action.

To get around this, we need a modified version of the model() method that can retrieve the array from the state object (even if it is nested several layers deep), modify the nested property value at the specified array index, and place the entire array back into the state object. So the method signature has to look like this:

Then, instead of model(‘guests[0].name’), we would call arrayItem(‘guests’, 0, ‘name’).

Now that you’ve seen the new method’s signature, you probably won’t have trouble inferring its implementation. Again, using lodash:

Now, you modify the input tag in your renderGuests() method to call the new array binder:

Add arrayItem() to bindModel.js:

… and get a reference to it in your component’s render() method:

This completes our full-featured two-way data binding library for ReactJS. To see the full source for this example, go to Feel free to leave questions in the comment section below.

Leave a Reply

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