React two way data binding with LinkedStateMixin

This is basic, two way data binding should come out of the box (like in Angular). In React you need an additional JavaScript file, fine.

From the official documentation it is not well explained how do it by just using the provided JS file: https://facebook.github.io/react/docs/two-way-binding-helpers.html (maybe I'm just dumb)

At the time of this writing I'm using React v0.14.3

1. Include the JS

Head to the download page: https://facebook.github.io/react/downloads.html and get the React with Add-Ons version. Include it into your project, just substitute your current react.js with the new react-with-addons.js

2. Add this line to your component

mixins: [React.addons.LinkedStateMixin]

var MyComponent = React.createClass({
    mixins: [React.addons.LinkedStateMixin],
    render:function(){    
        return (...);
    }
});

Now you'll be able to use with inputs, for instance:

var MyComponent = React.createClass({
    mixins: [React.addons.LinkedStateMixin],
    getInitialState:function(){
        return{
            customVar:''
        }
    },
    render:function(){
        return (
            <div>
                <input type="text" valueLink={this.linkState('customVar')} />
                <br />
                Print it: {this.state.customVar}
            </div>
        );
    }
});

About Rick

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*