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
TICK Stack Monitoring for the Non-Technical
TICK – Telegraf, Influx, Chronograf, and Kapacitor – is a method of monitoring your systems and applications. In this article, I discuss in non-technical terms what the difference is between TICK and Prometheus Grafana A […]
Design Systems, Part 1 • Introduction
Business leaders need a practical guide to plan and execute Design System Initiatives. The aim of this series is to be that guide. This installment introduces terms and definitions as a primer on Design Systems.
ML for Translating Dysarthria Speech (Pre-Part 1)
What is Dysarthria? Per the Mayo Clinic, Dysarthria occurs when the muscles you use for speech are weak or you have difficulty controlling them. Dysarthria often causes slurred or slow speech that can be difficult […]
Develop Quality Code
As software continues to dominate every facet of our lives, developers are faced with an ever-increasing pressure to produce bug free code. The responsibility of clean quality software falls upon everyone that is involved in […]