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