Next we're going to use EcmaScript 6 (ES6) with our calendar appointments app. It’s also known as ES2015. It hasn’t been completely implemented in all browsers, so it needs to be transpiled into ES5 by something like Babel, which is what the react-rails gem does.
ES6 introduced a lot of interesting new features like constants, block scoping, arrow functions, and classes which have made JavaScript a more powerful language.
By default, the react-rails gem uses ES5. It’s the version of Javascript most commonly implemented in browsers.
But using ES6 is also easy. We don’t need to change any config or setting in our app, we can simply write ES6 code and react-rails will take care of it.
Let’s start by looking at some ES6 code that react-rails can generate for us. The gem includes a component generator which you can use from the command line to make components.
You can specify the language you want. By default it’s ES5, but you can also choose ES6 or coffeescript.
We have a class here called Label which extends React.Component. React.Component is an abstract base class, and here we’re subclassing it.
Let’s compare this to our Appointments component which is written in ES5.
We have a variable called Appointments which calls React.createClass, whereas in the Label component we have a class which extends React.Component The way of writing the render function inside that is almost the same as ES5. There’s a shorthand here. We don’t need to write render: function(). We can just write render().
And the Label component also has something called propTypes which React uses for type checking - you can specify the data types of your components’ props. We haven’t used them yet but they are a useful way of debugging and avoiding a lot of bugs. We’ll talk about them in just a minute.
But first I want to quickly demonstrate using this ES6 Label component in our app.
Let’s put it on the index view. We can render it in exactly the same way we did with the ES5 components using the react_component helper method:
= react_component('Label', label: 'Enter a title, date and time')
We pass it the name of the component Label and its prop. And if we refresh the page we can see the label:
We can also nest the component in the same way as we did with ES5. So let’s move it and put it in the appointment form component: Nested ES6 component
So now we've seen that the react-rails gem has good support for ES6. You don't have to use it, but if you wish you can use ES6 components without changing any configuration.
Now let’s have a quick look at proptypes.
Our Label component has one prop called label with proptype string. That means when you use this component, React expects the label prop’s value to be a string, not a number or boolean or any other type.