React: Get set and go

I went through various tutorials and was puzzled how I was going to use React in my projects? It was hard to find a good tutorial that would teach how to install React. I might be a slow learner perhaps. However, we need stuff that would help us move forward, don’t we?

This tutorial focusses mainly on how to set things up to make React work. We all are fascinated with different features that React brings to the plate. Let’s see how we can take advantage of those features in our projects.

Let’s setup React!

For now I will not talk about React and it’s basic fundamentals. As of now, it is some library which requires: 1. React (of course), 2. Babel (very important transpiler tool), and 3. Webpack (a tool that helps us write modern JavaScript for not so modern browsers). If you don’t want to spend time on setting them manually, there is a readymade tool available for you. All you need is node and npm and you can easily setup a React project.

sudo npm install -g create-react-app
create-react-app {project name}
cd {project-name}
npm start

That’s it!

You can stop reading just right here. However, if you’re interested in setting things up manually, continue reading below…

 

We are looking for something else, aren’t we? How about we we create a simple project first with react and react-dom as dependencies?

npm init
npm install --save react react-dom

We have installed react and react-dom libraries and added them as dependencies in our package.json file. Our next steop is to enable ES6 and JSX.

(In case, if you’re not sure what ES6 and JSX are…)

JSX or JavaScript XML is a syntax introduced by Facebook in React. It’s new way of writing HTML within JavaScript. We will learn more about it in upcoming tutorials.

ES6 or ES2015 is the latest EcmaScript specification for JavaScript. All latest browsers now fully support ES2015. However, we still need our apps to run on older browsers which do not support ES2015 features. That’s where Babel and Webpack comes into picture.

Babel is a compiler that helps in compiling ES6 and JSX code into vanilla JavaScript. However, it’s incomplete without webpack. Webpack helps in resolving dependencies asynchronously. It means that if it sees an import in your JavaScript file, it will asynchronously load that file for you. It’s similar to what RequireJS did a couple of years ago.

We need to setup Webpack first, so that we can use Babel with it.

sudo npm install webpack -g

We will create a webpack config file which will be used to bundle our main.js file. Our React code sits inside main.js.

Let’s setup a set of directories where our code will be placed.

mkdir -p public/static/js
cd public/static/js

Create an empty main.js file inside this folder.

Navigate back to public folder and add index.html. This page will be served once node server has started. Insert following HTML in index.html:

<html>

<head>
<title>Demo React App</title>
</head>
<body>
<div class="title">This is a demo react app</div>
<div id="app">
    <!-- This is where your react component(s) will load -->
</div>
<script src="static/js/bundle.js"></script>
</body>

</html>

If you’ve noticed, we have included bundle.js file instead of main.js file. This is because webpack compiles main.js into bundle.js.

To create bundle.js we need a webpack configuration. Again, navigate to your project’s root folder and create webpack.config.js file with following configuration:

module.exports = {
     entry: "./public/static/js/main.js",
     output: {
          path: __dirname + "/public/static/js", // Output in same folder
          filename: "bundle.js"
     },
     module: {
          loaders: [
               { test: /\.css/, loader: "style!css" } // This is just for loading css
          ]
     }
};

Bundle your main.js using following command:

webpack --progress --colors

By now your folder structure should look like this:

screen-shot-2017-01-15-at-11-55-35-am

Let’s configure Babel now:

npm install --save-dev babel-loader babel-core babel-plugin-transform-react-jsx

We’ll edit our webpack.config.js file and add babel-loader to webpack loaders.

module.exports = {
     entry: "./public/static/js/main.js",
     output: {
          path: __dirname + "/public/static/js", // Output in same folder
          filename: "bundle.js"
     },
     module: {
          loaders: [
               { test: /\.css/, loader: "style!css" }, // This is just for loading css
               {test: /\.jsx/, loader: "babel-loader", exclude: "node_modules"}, // For JSX files
               {test: /\.js/, loader: "babel-loader", exclude: "node_modules"} // For JS files
          ]
     }
};

To make babel work, we need a config file for babel. Place a .babelrc configuration file in your root folder and add following configuration in it.

{
     "presets": []
}

Wondering why presets have been assigned an empty array? This is because we haven’t configured babel presets yet. To compile ES6 and JSX for react, we need to install babel presets: babel-preset-react and babel-preset-es2015.

npm install --save-dev babel-preset-react babel-preset-es2015

There!

The presets have been installed. Let’s enable them.

{
     "presets": ["react", "es2015"]
}

Phew!
Our major task’s done!

Before we start writing any code, let’s create a node server. That is most important part as we need to serve our index.html.

npm install --save express

Create an app.js file in your root folder and add following code to it:

let express = require("express");
let app = express();

app.use(express.static(__dirname + "/public"));

app.listen(8080, () => {
     console.log("Node server started on port 8080 ...");
});

Type following command on terminal to start the server

node app

Head over to your browser and type http://localhost:8080.

Voila! Our project is setup. Let’s write some react code and see if everything works fine.

Head over to public/static/js folder and create a demo.jsx file. Add following code in it:

import React from "react";
class ReactDemo extends React.Component {
render() {
return (
<div>This is a react component</div>
);
}
}

export default ReactDemo;

Head over to main.js file and add following code:

import ReactDemo from "./ReactDemo.jsx";
import React from "react"; // This needs to be there in every file using react APIs
import ReactDOM from "react-dom";

ReactDOM.render(, document.getElementById("app"));

That’s it!

Open a new terminal and re-run webpack to refresh your bundle. Then head over to your browser and refresh your page.

You’ll see that your first React code worked just fine.

By now your project folder should look like below:

screen-shot-2017-01-15-at-1-36-19-pm

Few words of wisdom:

It’s always a good idea to compress bundle.js file as (over a period of time) it becomes bigger and bigger.

We should also enable webpack bundle source maps and include them in index.html. This makes JavaScript debugging a piece of cake (go figure…).

For debugging React components, Facebook has created React devtools. It can be downloaded and added from chrome webstore or firefox add-ons.

You must be wondering: do we have to run webpack everytime we do a small change in our js files? Not really. You can enable watch for webpack.

webpack --progress --colors --watch

It is also a good idea to add webpack as part of your gulp build process.

Enough spoken! Let’s head over to our first react tutorial.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s