Deep-Path Data Bindings in React (like Angular)

 

Screen Shot 2016-04-12 at 3.50.20 PM

JSFiddle: https://jsfiddle.net/michaelmakarov/xo3ywx85/

Recently, we rebuilt Sonar‘s entire front-end interface in ReactJS.  With users getting hundreds of messages a minute, a fast, slick, single-page application was necessary. The move to React was great—we’ve enjoyed working with it and it has helped us accomplish our goals quickly. However, since our tech team comes from a background in AngularJS, we found React’s data bindings to be much less convenient.

Data bindings in React required us to code separate ‘binding’ methods, which we weren’t used to with its counterpart, Angular. In Angular, we would simply add a model attribute to our components and the job was done. How bindings worked in React when we got started (the ‘handleChange’ method):

To be fair, since we started building our application, React has made bindings a bit easier with ReactLink. However, ReactLink doesn’t allow for deep-path links (i.e. account.owner.email). Angular supports deep-path links out of the box.

To solve our problem, and to be able to build our interfaces faster, we decided to create Angular-like bindings in ReactJS. We created a new component called “MagicInput”. With MagicInput, we would pass the current ‘scope’ and a deep path, and the binding would be done! To construct data bindings now, all we write is this:

With just three words, we can change the email of the account owner in the current scope.

See the code of MagicInput below. You’ll notice that on line 6 sets the parent state.

In line 5, you’ll see an helper called changeByArray, where we pass the object that we want to change, the path in the object as an array, e.g. [‘account’, ‘owner’, ’email’] and the value we’d like to set it to.

At Sonar, we expanded upon the basic code above to support other input elements and attributes. For example, we can make input values be required, add classes, and even go as far as to require emojis 😄.

If you’d like to play with it in Javascript, check out this JSFiddle: https://jsfiddle.net/michaelmakarov/xo3ywx85/

We’re sure there are other options out there to accomplish easy deep-path bindings in React, but MagicInput worked out really well for us. Feel free to use it in your codebase, and more importantly, tell us your thoughts?

Credits: Neeharika Bhartiya, Aaron Garvey

Share this:

Leave a Reply

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