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:

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:

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.

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!

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

Resources

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

Have fun!