React statics with ES6 classes

Does the statics object work with ES6 classes in React?

class SomeComponent extends React.Component {

  render() {
    // ...
  }

}

React.statics = {
  someMethod: function() {
    //...
  }
};

Something like the above gives me undefined method someMethod when I do SomeComponent.someMethod()


Solution 1:

statics only works with React.createClass. Simply declare the method as a static class method:

class SomeComponent extends React.Component {

  static someMethod() {
    //...
  }

  render() {
    // ...
  }

}

Regarding

React.statics = { ... }

You are literally creating a statics property on the React object. That property does not magically extend your component.

Solution 2:

Although statics only works for React.createClass, you can still write static methods in ES6 notation. If you are using ES7, then you can also write static properties.

You can write statics inside ES6+ classes this way:

class Component extends React.Component {
    static propTypes = {
    ...
    }

    static someMethod(){
    }
}

Or outside the class like this:

class Component extends React.Component {
   ....
}

Component.propTypes = {...}
Component.someMethod = function(){....}

If you want to write it like the former, then you have to set stage: 0 on Babel (since its experimental).

Solution 3:

Statics can be accessed without having to instantiate a component. Normally they aren't that useful but there are a few special cases. For example into routing when you leave the current page with doing a ACTION PERFORM then through Statics methods you can hold/ASKED the user whether he really want to leave the page. For example:

exampleComponent= React.createClass({
statics:{
        willTransitionFrom: function(transition,component){
            // check any state here or value Aasked the user.
        }
    }
});

It exposes willTransitionTo and willTransitionFrom lifecycle methods. both are particular is useful as a static as you can actually cancel a transition before instantiating a component.