Skip to content

A React mixin used to simplify the binding between components and data stores.

Notifications You must be signed in to change notification settings

golmansax/react-bind-mixin

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

React Bind Mixin

Build Status Code Climate Test Coverage

A React mixin used to simplify the binding between components and data stores. Can be plugged into virtually any Flux implementation!

Sample Usage

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

Makes testing easy!

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');

Installation

# Node
npm install react-bind-mixin --save

About

A React mixin used to simplify the binding between components and data stores.

Resources

Stars

Watchers

Forks

Packages

No packages published