ReactJS Mixins

Nov 21st, 2015

Components are the best way to reuse code in React, but sometimes very different components may share some common functionality. These are sometimes called cross-cutting concerns. React provides mixins to solve this problem.

Example:

Let’s create a simple mixin that uses lifecycle methods for using in two components.

<!DOCTYPEhtml><html><head><metacharset="UTF-8"><title></title><scripttype="text/javascript"src="http://fb.me/react-0.12.2.js"></script><scripttype="text/javascript"src="http://fb.me/JSXTransformer-0.12.2.js"></script></head><body><scripttype="text/jsx">varReactMixin={getInitialState:function(){return{count:0}},componentWillMount:function(){console.log('will mount');},incrementCount:function(){this.setState({count:this.state.count+1});}}varApp=React.createClass({render:function(){return(<div><Buttontxt="this is the button"/><br/><Labeltxt="this is the label"/></div>);}});varButton=React.createClass({mixins:[ReactMixin],render:function(){return<buttononClick={this.incrementCount}>{this.props.txt}-{this.state.count}</button>}});varLabel=React.createClass({mixins:[ReactMixin],componentWillMount:function(){setInterval(this.incrementCount,1000);},render:function(){return<label>{this.props.txt}-{this.state.count}</label>}});ReactDOM.render(<App/>,document.body);</script></body></html>