React.createClass vs extends Component

These two ways depend on if you are using ES6 syntax or not, and they also change the way you set up your initial state.

When using ES6 classes, You should initialize state in the constructor.

When using React.createClass you have to use the getInitialState function.

ES6 Class Syntax:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { /* initial state, this is ES6 syntax (classes) */ };
  }
}

ES5 React.CreateClass syntax:

var MyComponent = React.createClass({
  getInitialState() {
    return { /* initial state */ };
  },
});

These will both work the same way to set up initial state.

Leave a Comment