childContextTypes in ES6

13,594

Solution 1

Since you are using Babel anyway, you can use static (ES7) in your code like this:

export default class A extends React.Component {

  static childContextTypes = {
    name: React.PropTypes.string,
  }

  getChildContext() {
    return { name: "Jonas" }
  }

  render() {
    return <B />
  }
}

More info: React on ES6+

Solution 2

The issue is that childContextTypes needs to be defined on the "class", which is what static does. So these two solutions seem to work:

class A extends React.Component {
  constructor() {
    super(...arguments);

    this.constructor.childContextTypes = {
      name: React.PropTypes.string.isRequired
    };
  }
}

Or

class A extends React.Component {

}

A.childContextTypes = {
  name: React.PropTypes.string.isRequired
};
Share:
13,594

Related videos on Youtube

Chris G.
Author by

Chris G.

Updated on September 14, 2022

Comments

  • Chris G.
    Chris G. over 1 year

    How would you write the object childContextTypes in ES6?

    var A = React.createClass({
    
        childContextTypes: {
             name: React.PropTypes.string.isRequired
        },
    
        getChildContext: function() {
             return { name: "Jonas" };
        },
    
        render: function() {
             return <B />;
        }
    });
    
    • Bergi
      Bergi
      Does this help? Not sure if it's a duplicate
  • Jacob Davis-Hansson
    Jacob Davis-Hansson about 8 years
    The more-info blog page has moved to babeljs.io/blog/2015/06/07/react-on-es6-plus
  • cutemachine
    cutemachine about 8 years
    Thank you jakewins. Updated the link accordingly.
  • John Xiao
    John Xiao almost 8 years
    There is a syntax error at getUser: () => ({ name: 'Bob' })