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
Android Development for iOS Developers
Android development has greatly improved since the early days. Maybe you tried it out when Android development was done in Eclipse, emulators were slow and buggy, and Java was the required language. Things have changed […]
Add a custom object to your Liquibase diff
Adding a custom object to your liquibase diff is a pretty simple two step process. Create an implementation of DatabaseObject Create an implementation of SnapshotGenerator In my case I wanted to add tracking of Stored […]
Keeping Secrets Out of Terraform State
There are many instances where you will want to create resources via Terraform with secrets that you just don’t want anyone to see. These could be IAM credentials, certificates, RDS DB credentials, etc. One problem […]
Validating Terraform Plans using Open Policy Agent
When developing infrastructure as code using terraform, it can be difficult to test and validate changes without executing the code against a real environment. The feedback loop between writing a line of code and understanding […]