Search code examples
javascriptreactjsmixinsreactjs-flux

Export React mixin in a separated file


I am trying to separate the SetIntervalMixin into a different file that the component class file. Maybe I am not fully understand how module.export works but... If I do like this:

module.exports = {
 componentWillMount: function() {
   this.intervals = [];
 },
 setInterval: function() {
   this.intervals.push(setInterval.apply(null, arguments));
 },
 componentWillUnmount: function() {
   this.intervals.map(clearInterval);
 }
};

inside a SetIntervalMixin.js, then it works fine using from the component:

var SetIntervalMixin = require('../util/mixins/SetIntervalMixin')

But if I write it like this:

var SetIntervalMixin = {

  componentWillMount: function() {
    this.intervals = [];
  },
  setInterval: function() {
    this.intervals.push(setInterval.apply(null, arguments));
  },
  componentWillUnmount: function() {
    this.intervals.map(clearInterval);
  }
};

module.export = SetIntervalMixin;

It doesn't work (undefined when trying to call setInterval()). I think something is missing after:

SetIntervalMixin = ...

Like when you define a component, you use:

var yourComponent = React.createClass(...

Is there is something similar like a React.createMixin(.. ? Or how would be the best way to do this.

Thanks.


Solution

  • Your code is right, you just have a typo in the second version (should be module.exports instead of module.export):

    var SetIntervalMixin = {
    
      componentWillMount: function() {
        this.intervals = [];
      },
      setInterval: function() {
        this.intervals.push(setInterval.apply(null, arguments));
      },
      componentWillUnmount: function() {
        this.intervals.map(clearInterval);
      }
    };
    
    module.exports = SetIntervalMixin;