Developing React.js Components Using ES6

Last updated: August 29, 2015

React.js is the greatest thing to happen to front-end development in a long time. It is fast, it allows us to break our application into bite-sized chunks and has a tiny learning curve.

In this article we will be using ECMAScript 6 classes to write our React.js components. This means they will be easier to read and look nicer, even if they are prototypical inheritance syntactical sugar.

Before we begin

I want to preface this article with: this is not a crash course on how to use React.js.

This article assumes you are familiar with basic React.js concepts and you’re curious about writing React components using ES6. So be aware certain aspects of this article will be foreign to you if you have not used React.js before nor read the documentation.

There are tonnes of great resources out there for getting started with React. So, I do not recommend diving right into ES6 if you’re not familiar with the basic concepts first.

The getting started page on React’s website is a great resource I recommend reading.

Installing React

Create a new folder anywhere of your choosing and provided you have NPM installed on your machine, run this command on the command line: npm install react

Screen Shot 2015-02-18 at 12.38.06 pm

What are we building?

We are building an example application that allows us to supply a persons name and put a styled hat on them. Original, right?

We will be defining two separate files: one for the person and one for the hat. It is a good habit to get into by breaking your application up into small managed chunks. This is the entire premise of which React.js operates upon.

We are not going to be building anything interactive. I am just showing you a quick silly example of how you can use ES6 classes to develop React.js components. This article assumes you are familiar with React.js already, remember?

Firstly, lets define our components

Every new React component that you create will extend React.Component. This is a requirement or your components will not work.

The in-browser transformer will take care of ensuring that our classes work for older browsers and with React itself by transpiling it on the fly (unless of course you pre-compiled your classes).

// components/Hat.js
class Hat extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        var hatClass = 'hat ' + this.props.type;
        return (
            <div className={hatClass}></div>
        );
    }
}
// components/Person.js
class Person extends React.Component {
    // Constructor
    constructor(props) {
        super(props);
        this.state = {name: props.name};
    }

    // This method will allow us to change the current name of the person
    setName(name) {
        this.setState({name: name});
    }

    render() {
        var hat = this.props.hat;
        var hatLabel;

        if (hat === 'none') {
            hatLabel = 'I am not wearing a hat.';
        } else {
            hatLabel = 'I am wearing a '+hat+' style hat.';
        }

        return (
            <div className="person">
                <Hat hatType={hat} />
                <div className="personLabel">My name is {this.state.name} and {hatLabel}</div>
            </div>
        );
    }
}
Person.defaultProps = { name: 'anonymous', hat: 'none'};

Now that we have our two separate component files, we need to create our main application file which will “Reactify” our DOM.

For brevity we will be calling this file app.js.

// app.js
(function() {
    'use strict';

    React.render(<Person name='Dwayne' />, document.getElementById('app'));
})();

Before any of this does anything, we need some basic HTML for this example to even work.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Hat Wearing App</title>
        <script src="node_modules/react/dist/react.js"></script>
        <script src="node_modules/react/dist/JSXTransformer.js"></script>
        <meta name="viewport" content="width=device-width">
    </head>

    <body>
        <div id="app"></div>
        <script type="text/jsx;harmony=true" src="components/Hat.js"></script>
        <script type="text/jsx;harmony=true" src="components/Person.js"></script>
        <script type="text/jsx" src="app.js"></script>
    </body>
</html>

A note on using ES6 with the in-browser JSXTransformer

Using ES6 syntax with the in-browser transformer requires enabling a flag in the type attribute called: harmony

As you can see in the above example we specify: type="text/jsx;harmony=true". Without this flag, the compiler will throw an error. The value must be true, otherwise it will default to false.

This is the number one mistake first-timers attempting to use ES6 syntax with React.js will make. The harmony flag is not documented particularly well, so it is easy to get caught out by not including it.

While the in-browser transformer is great for prototyping purposes, it is not advisable for you to use it in production. Always compile your code before deploying to production.

A note on mixins

If you do decide to use ES6 syntax for writing your React.js applications, keep in mind that you cannot use mixins. This is a limitation with ES6 itself and lack of native support for mixins and not React.js.

Keep this limitation in mind before you go writing your React.js components the ES6 way. If you need to use mixins there are alternative workarounds you can pursue (not covered here).

Differences between using ES6 and non-ES6

Besides the above downside of not being able to use mixins with ES6 classes, there are only a couple of differences to be aware of if you are going down the ES6 path.

When using classes, getInitialState is replaced in favour of using an instance property on the class itself called state. The getDefaultProps and propTypes values are merely properties of the constructor (as you can see at the bottom of Person.js).

With exception of the above slight API changes, everything else is essentially the same as it previously was, you just write the methods in context of a class.

So previously for the render method you would write render: function() {}code> because a class was defined in object curly braces for the createClass method. Now you can just write render() {} which is the same thing, but nicer to look at.

Conclusion

I hope this opens up new opportunities for you to write React.js components in future projects using React. You cannot deny that the ES6 syntax is definitely cleaner and easier to write. If you are lazy like me, all of the above example code is available for download here on Github.

While this might not have been an overly in-depth article on using ES6 syntax with React.js, you can see how how easy it is to develop React.js components using ES6 syntax.

I have no doubt we will see greater ES6 support added into future versions of React, but for now, this is a great start. Happy coding.

 

Dwayne

 

2 thoughts on “Developing React.js Components Using ES6

  1. Thanks for the post. Just getting into React, coming from 15 years in very OOP Java. The whole “Always Composite, never Inherit” thing isn’t working for me. This should make the whole experience ‘much betta’

Leave a Reply

Your email address will not be published. Required fields are marked *