Notes of Maks Nemisj

Experiments with JavaScript

React.js: propTypes in ES6/ES2015 components

If you’ve decided to move react components to es6/es2015 syntax you’ve might found out that defining propTypes and contextTypes is not that seamless as it was. Babel@6.7.7 doesn’t yes support static properties on Classes and the most evident way to use propTypes is to append them to the class at the end:

class SomeComponent extends React.Component {
  render() {
  }
}

SomeComponent.propTypes = {
  text: React.PropTypes.string
};

Though there is a little trick to do it inline in the class. Thankfully bable@6.7.7 supports static getters and setters which we can use for that:

class SomeComponent extends React.Component {

  static get propTypes() {
    return {
      text: React.PropTypes.string
    }
  }

  render() {
  }

}

The same applies to contextTypes.

Now you can choose which method to use 🙂

, , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *