Apr 26, 2017

Two-way Data Binding in ReactJS – Part II

Nested State

In Part I, we learned how to bind top-level state properties to form elements in JSX, so that updates to those elements automatically updated state and vice versa. However, the method we used breaks down when the structure of our state object is more complex; for example:

Our method retrieves the value from state[key], and updates the value with setState({ [key]: /* … */ }), which means we can’t bind an element like this:

… because this.state[‘guest1.name’] is undefined.

While it might make sense to “flatten” the structure of your state object in this specific case, you’re going to need support for nested objects at some point, especially if you want to work with REST data.

Fortunately, lodash can “drill down” into nested objects to find specific properties; so adding this capability to our binder method is as simple as calling lodash’ get() and set() methods:

Now we can use dot (.)- delimited property names in our component JSX:

To see the full example, browse this source at https://github.com/abraham-serafino/react-data-binding/tree/Part-II.

In Part III, we’ll round out the features of our new library by adding support for variable-length arrays.

About the Author

Object Partners profile.

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

Leave a Reply

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

Related Blog Posts
Using Conftest to Validate Configuration Files
Conftest is a utility within the Open Policy Agent ecosystem that helps simplify writing validation tests against configuration files. In a previous blog post, I wrote about using the Open Policy Agent utility directly to […]
SwiftGen with Image & Color Asset Catalogs
You might remember back in 2015 when iOS 9 was introduced, and we were finally given a way to manage all of our assets in one place with Asset Catalogs. A few years later, support […]
Tracking Original URL Through Authentication
If you read my other post about refreshing AWS tokens, then you probably have a use case for keeping track of the original requested resource while the user goes through authentication so you can route […]
Using Spring Beans in a Kafka Streams ExceptionHandler
There are many things to know before diving into Kafka Streams. If you haven’t already, check out these 5 things as a starting point. Bullet 2 mentions designing for exceptions. Ironically, this seems to be […]