React.Component vs React.createClass

React.createClass - method to create component classes

For better use with ES6 modules by extends React.Component, which extends the Component class instead of calling createClass

Few differences between both are,

Syntax : React.createClass:

var MyComponent = React.createClass({ });

React.Component:

export default class MyComponent extends React.Component{ }

getInitialState() : React.createClass: Yes React.Component: No

constructor() : React.createClass: No React.Component: Yes

propTypes Syntax : React.createClass:

var MyComponent = React.createClass({
    propTypes: { }
});

React.Component:

export default class MyComponent extends React.Component{ }
MyComponent.prototypes = { }

Default Properties : React.createClass:

var MyComponent = React.createClass({
    getDefaultProps(): { return {} }
});

React.Component:

export default class MyComponent extends React.Component{ }
MyComponent.defaultProps = { }

state : React.createClass:

State changes can be made inside getInitialState() function

React.Component:

State changes can be made inside constructor(props) function

this :
React.createClass:

automatically bind 'this' values.
Ex: <div onClick={this.handleClick}></div>
'this' can be accessed by default in handleClick function

React.Component:

whereas here we need to bind explicitly,
Ex: <div onClick={this.handleClick.bind(this)}></div>

There are 2 ways of doing the same thing.

React.createClass is a function that returns a Component class.

MyComponent = React.createClass({
  ...
});

React.Component is an existing component that you can extend. Mainly useful when using ES6.

MyComponent extends React.Component {
  ...
}

The only React.createClass functionality that isn't supported by MyComponent extends React.Component is mixins.

to do getInitialState() you can do:

class MyComponent extends React.Component {
  constructor(props, context) {
    super(props, context);

    // initial state
    this.state = {
      counter: 0
    };
  }

  ...
}

or if you use a transpiler like babel, you can get

class MyComponent extends React.Component {
  state = {
    counter: 0
  }

  ...
}

Instead of auto-binding provided by createClass, you could explicitly bind using .bind(this) like you have shown above, or use the fat arrow ES6 syntax:

class MyComponent extends React.Component {
  onClick = () => {
    // do something
  }
  ...
}

Instead of putting things in componentWillMount, you could put things in constructor like so:

class MyComponent extends React.Component {
  constructor(props, context) {
    super(props, context);

    // what you would have put in componentWillMount
  }

  ...
}

There are way more details in the React documentation themselves, but basically the only additional functionality that React.createClass buys is mixins, but afaik anything you could have done with mixins can be done with context and higher ordered components.

Tags:

Reactjs