React Mixin example
A mixin in the component specification is an array. A mixin can share the lifecycle events
of your component and you can be assured that the functionality will execute during
the proper time during the component’s lifecycle.
by Enrico Rossini
March 07, 2016
HTML
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
JavaScript
var SetIntervalMixin = {
componentWillMount: function() {
this.intervals = [];
},
setInterval: function() {
this.intervals.push(setInterval.apply(null, arguments));
},
componentWillUnmount: function() {
this.intervals.map(clearInterval);
}
};
var TickTock = React.createClass({
mixins: [SetIntervalMixin], // Use the mixin
getInitialState: function() {
return {seconds: 0};
},
componentDidMount: function() {
this.setInterval(this.tick, 1000); // Call a method on the mixin
},
tick: function() {
this.setState({seconds: this.state.seconds + 1});
},
render: function() {
return (
<p>
React is running for {this.state.seconds} seconds
</p>
);
}
});