React: Convert React class to ES6 class error when use context

Created on 14 Sep 2015  路  8Comments  路  Source: facebook/react

I have a Class A created by createClass, while after I transform it into a ES6 class, I caught an err:

//Original class code
var A = React.createClass({

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

  getChildContext: function() {
       return { name: "Jonas" };
  },

  render: function() {
       return <B />;
  }
});
// ES6 class
class A extends React.Component {
  childContextTypes: { 
    name: React.PropTypes.string
  },

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

  render () {
    return <B />;
  }
}

May be something wrong in the childContextTypes defining method?

Most helpful comment

The correct way:

class A extends React.Component {
  getChildContext () {
    return { name: "Jonas" };
  }

  render () {
    return <B />;
  }
}

A.childContextTypes = { 
  name: React.PropTypes.string
};

Note that I removed comma after getChildContext method and moved childContextTypes to declare attribute on the component class.

All 8 comments

The correct way:

class A extends React.Component {
  getChildContext () {
    return { name: "Jonas" };
  }

  render () {
    return <B />;
  }
}

A.childContextTypes = { 
  name: React.PropTypes.string
};

Note that I removed comma after getChildContext method and moved childContextTypes to declare attribute on the component class.

@andreypopp Thank you, but only in this way? Is there a better way?

@iostalk if you are using Babel with "stage": 0 option then you can take advantage of static class property initializers:

class A extends React.Component {

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

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

  render () {
    return <B />;
  }
}

@andreypopp Thank you very much!

Thanks, @andreypopp.

@andreypopp Side question from you example, does using the _static class option_ makes sense for the getChildContext method? I.e:

class A extends React.Component {

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

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

  render () {
    return <B />;
  }
}
-  getChildContext () {
+  static getChildContext () {

@oliviertassinari it needs to be a prototype method (non-static). It can also use state and props.

@brigand Right, it doesn't work with the static: http://www.webpackbin.com/4JKCVq7Cb. Thanks! (I was having issues with the class-methods-use-this rule of eslint)

Was this page helpful?
0 / 5 - 0 ratings