How to create React components

July 11, 2016

There are now three ways to create React components in JavaScript. Let’s take a quick look at each of them and discuss the pros and cons!

Create React Components with React.createClass

The first way, and the way Facebook still uses is the createClass method. It looks something like this:

var MyComponent = React.createClass({
  render: function() {
    return (
      <div>
        {this.props.name}
      </div>
    );
  }
});

This is my favorite way of creating components. As we explore the other options you’ll see some of the extra boilerplate or limitations with them.

Creating Components with ES6 Classes

With ES6, we can now create react components with ES6 classes. They look like this:

export class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        {this.props.name}
      </div>
    );
  }
}

While I do like the ES6 class syntax, there are a few things I don’t love about creating components this way.

  • There is no more getInitialState method. All the logic you would put in getInitialState now must go in the constructor.
  • propTypes and defaultProps are defined as properties on the constructor instead of in the class body.
  • No mixin support.
  • No more autobinding. This means that you either have to explicitly bind this or use an arrow function. Example below.
    // You can use bind() to preserve this
    <div onClick={this.tick.bind(this)}>

// Or you can use arrow functions <div onClick={() => this.tick()}>

Creating Stateless React Functions

I find these really cool. If your component doesn’t have its own state, you can just use regular JavaScript functions!

function MyComponent(props) {
  return <div>{props.name}</div>;
}

If you want to get really fancy with it, you can use ES6 arrow functions!

const MyComponent = (props) => <div>{props.name}</div>;

Resources

If you’re looking to learn more, here are some resources!

Have fun!