Using React the ES5 and ES6 Way
There are two ways to use React, the old createClass
or the fancy ES6 extend
way. We should go the ES6 way since it gives much more native JavaScript feeling rather than react feeling when you coding. But there are so much examples out there which follows the classic way. It is good to give a look to both of them side by side to provide a more clear understanding. Yes, you can apply ES6 syntax to createClass
as well, but we won’t cover that here.
1. Declare a new component:
1 | //ES5 |
1 | //ES6 |
There is a fancy introduced in 1.4 with the concept of “stateless component”. Many benefits will gain via this way, but this is not the topic here.
1 | //ES6, stateless functional component |
2. props and state gets better
props
with the ES6 take advantage of the new syntax, makes it more JavaScript-favor, it’s now more like a built-in property of a class rather than some return value from a function.
1 | //ES5 |
1 | //ES6 |
1 | //Another way via ES6 |
3. context may a little bit different
In fact, this section has nothing to do with the syntax, it is something about the createClass
. It will auto-bind the this
, but we need to manage this via ES6.
1 | //ES5 |
We have multiple ways to do this via ES6.
1 | //ES6 |
1 | //ES6 bind this in the constructor |
Now my personal favourite, the truely ES6 approach via arrow function
.
And isn’t this the most usage of arrow function?
1 | //ES6 with arrow function |
It works simply because arrow functions can use the same lexical scope as the codes around it.
4. End of story
React is fun to use. Hope it helps some one. You can see by the above examples that when you use the ES6 syntax, most of the time, you are dealing with the JavaScript syntax itself rather than learning some react built-in functions. Which feels super good.
Thanks for reading!
Follow me (albertgao) on twitter, if you want to hear more about my interesting ideas.