Fixing error: Warning: getInitialState was defined on a plain JavaScript class. This is only supported for classes created using React.createClass.

Let’s say you upgrade an old React component, like so:

class MyComponent extends React.Component {
  constructor() {
    super();
  }
 
  getInitialState() {
    return { test: 1 }
  }
 
  render() {
    render (<div>Hello World!</div>);
  }
}

When you go to use this, you will get this error:

Warning: getInitialState was defined on a plain JavaScript class. 
This is only supported for classes created using React.createClass.

React can apparently detect the difference between objects and new ES6 classes, and wants you to use a more conventional class construction technique.

The correct answer is to do what the error says, and move the contents of the getInitialState function into the constructor:

class MyComponent extends React.Component {
  constructor() {
    super();
 
    this.state = { test: 1 };
  }
 
  render() {
    render (<div>Hello World!</div>);
  }
}

Leave a Reply

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