A React mixin used to simplify the binding between components and data stores. Can be plugged into virtually any Flux implementation!
Given a Store with the following API:
var MyStore = {
addChangeListener: function (callback) {
// bind callback to changes to Store
},
removeChangeListener: function (callback) {
// remove callback binding
}
};
We can bind a React component to the Store in a simple way:
var BindMixin = require('react-bind-mixin');
var Component = React.createClass({
mixins: [BindMixin(MyStore, 'getStateFromStore')],
// this.props passed in for 'props'
// except for when called from componentWillReceiveProps (newProps passed in)
getStateFromStore: function (props) {
return {
// 'getValue' API is custom to the store implementation
value: MyStore.getValue(props.id)
};
},
render: function () {
return <div>{this.state.value}</div>;
}
});
Now the state of our component will be:
- initialized with the initial value of the Store
- updated when the Store is changed
- updated when props are changed
With this straight-forward implementation, it becomes trivial to test the component. Simply mock out the associated store functions. Below is an example using the Mocha/sinon test framework.
sinon.stub(MyStore, 'getValue');
MyStore.getValue.returns('Hello');
var component = React.addons.TestUtils.renderIntoDocument(<Component />);
expect(component.text).to.equal('Hello');
MyStore.getValue.returns('Goodbye');
expect(component.text).to.equal('Goodbye');
# Node
npm install react-bind-mixin --save