React/es6 difference between exports createClass and extends Component

I am starting out with react and es6 and and trying to determine the real difference between

export const Voting = React.createClass({ ... })

and

class Voting extends React.Component { ... }

It seems I can achieve the same desired effect with both (unless I am mistake, of course). I think I would prefer the second format if there is no difference, but I can't seem to figure out what the real difference is. Would appreciate any and all input, thanks!

Answers:

Answer

From the blog post that announced ES6 class support:

JavaScript originally didn't have a built-in class system. Every popular framework built their own, and so did we. This means that you have a learn slightly different semantics for each framework.

We figured that we're not in the business of designing a class system. We just want to use whatever is the idiomatic JavaScript way of creating classes.

In React 0.13.0 you no longer need to use React.createClass to create React components. If you have a transpiler you can use ES6 classes today.

So, both do the same thing (define a React component), but ES6 classes is the more native way to do it (no custom React boilerplate code) and as such it is much easier to reason about the code. This should be the preferred way of creating React components.

There are two notable differences between React.createClass and ES6 classes though (also mentioned in that blog post):

  • Autobinding - React.createClass autobinds all methods to the current instance. With ES6 classes you have to do that yourself.

  • Mixins - ES6 classes have no direct support for mixins like React.createClass did.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.