Use Higher order components over Mixins

Simple Example

  1. // With Mixin
  2. var WithLink = React.createClass({
  3. mixins: [React.addons.LinkedStateMixin],
  4. getInitialState: function () {
  5. return {message: 'Hello!'};
  6. },
  7. render: function () {
  8. return <input type="text" valueLink={this.linkState('message')}/>;
  9. }
  10. });
  11. // Move logic to a HOC
  12. var WithLink = React.createClass({
  13. getInitialState: function () {
  14. return {message: 'Hello!'};
  15. },
  16. render: function () {
  17. return <input type="text" valueLink={LinkState(this,'message')}/>;
  18. }
  19. });

Detailed Example

  1. // With Mixin
  2. var CarDataMixin = {
  3. componentDidMount: {
  4. // fetch car data and
  5. // call this.setState({carData: fetchedData}),
  6. // once data has been (asynchronously) fetched
  7. }
  8. };
  9. var FirstView = React.createClass({
  10. mixins: [CarDataMixin],
  11. render: function () {
  12. return (
  13. <div>
  14. <AvgSellingPricesByYear country="US" dataset={this.state.carData}/>
  15. <AvgSellingPricesByYear country="UK" dataset={this.state.carData}/>
  16. <AvgSellingPricesByYear country="FI" dataset={this.state.carData}/>
  17. </div>
  18. )
  19. }
  20. });
  21. // With HOC
  22. var bindToCarData = function (Component) {
  23. return React.createClass({
  24. componentDidMount: {
  25. // fetch car data and
  26. // call this.setState({carData: fetchedData}),
  27. // once data has been (asynchronously) fetched
  28. },
  29. render: function () {
  30. return <Component carData={ this.state.carData }/>
  31. }
  32. });
  33. };
  34. // Then wrap your component when you define it.
  35. var FirstView = bindToCarData(React.createClass({
  36. render: function () {
  37. return (
  38. <div>
  39. <AvgSellingPricesByYear country="US" dataset={this.props.carData}/>
  40. <AvgSellingPricesByYear country="UK" dataset={this.props.carData}/>
  41. <AvgSellingPricesByYear country="FI" dataset={this.props.carData}/>
  42. </div>
  43. )
  44. }
  45. }));