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
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 (