Skip to content

Latest commit

 

History

History
85 lines (76 loc) · 2.48 KB

03.mixins.md

File metadata and controls

85 lines (76 loc) · 2.48 KB

Use Higher order components over Mixins

Simple Example

// With Mixin
var WithLink = React.createClass({
  mixins: [React.addons.LinkedStateMixin],
  getInitialState: function () {
    return {message: 'Hello!'};
  },
  render: function () {
    return <input type="text" valueLink={this.linkState('message')}/>;
  }
});

// Move logic to a HOC
var WithLink = React.createClass({
  getInitialState: function () {
    return {message: 'Hello!'};
  },
  render: function () {
    return <input type="text" valueLink={LinkState(this,'message')}/>;
  }
});

Detailed Example

// With Mixin
var CarDataMixin = {
  componentDidMount: {
    // fetch car data and
    // call this.setState({carData: fetchedData}),
    // once data has been (asynchronously) fetched
  }
};

var FirstView = React.createClass({
  mixins: [CarDataMixin],
  render: function () {
    return (
      <div>
        <AvgSellingPricesByYear country="US" dataset={this.state.carData}/>
        <AvgSellingPricesByYear country="UK" dataset={this.state.carData}/>
        <AvgSellingPricesByYear country="FI" dataset={this.state.carData}/>
      </div>
    )
  }
});

// With HOC
var bindToCarData = function (Component) {
  return React.createClass({
    componentDidMount: {
      // fetch car data and
      // call this.setState({carData: fetchedData}),
      // once data has been (asynchronously) fetched
    },

    render: function () {
      return <Component carData={ this.state.carData }/>
    }
  });
};

// Then wrap your component when you define it.
var FirstView = bindToCarData(React.createClass({
  render: function () {
    return (
      <div>
        <AvgSellingPricesByYear country="US" dataset={this.props.carData}/>
        <AvgSellingPricesByYear country="UK" dataset={this.props.carData}/>
        <AvgSellingPricesByYear country="FI" dataset={this.props.carData}/>
      </div>
    )
  }
}));

Related links: