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.

Related Blog Posts
Natively Compiled Java on Google App Engine
Google App Engine is a platform-as-a-service product that is marketed as a way to get your applications into the cloud without necessarily knowing all of the infrastructure bits and pieces to do so. Google App […]
Building Better Data Visualization Experiences: Part 2 of 2
If you don't have a Ph.D. in data science, the raw data might be difficult to comprehend. This is where data visualization comes in.
Unleashing Feature Flags onto Kafka Consumers
Feature flags are a tool to strategically enable or disable functionality at runtime. They are often used to drive different user experiences but can also be useful in real-time data systems. In this post, we’ll […]
A security model for developers
Software security is more important than ever, but developing secure applications is more confusing than ever. TLS, mTLS, RBAC, SAML, OAUTH, OWASP, GDPR, SASL, RSA, JWT, cookie, attack vector, DDoS, firewall, VPN, security groups, exploit, […]