Learning React: Setting up a minimal React development environment

Andy Neale
9 min readSep 16, 2016

--

Join me on a journey to learn React…

Who is this for

I’ve been a web developer for more than fifteen years. I’m familiar with HTML and CSS, I’ve done plenty of work with jQuery, some with AngularJS, I’ve done server-side development with NodeJS, and I know enough to get by with tools like Gulp and Grunt and npm.

Now I want to learn React. Building web applications with jQuery is fine — in fact, until your app gets too big, it’s quick, easy and indeed fun — but after a while it starts to get very difficult to keep track of which bits of code are responsible for managing which bits of the UI, and soon you find yourself looking for an alternative.

For some people, AngularJS might be the answer. I’ve done some development with Angular, and whilst it’s capable of some pretty awesome things, it’s also capable of baffling the heck out of me. So I started reading up about React, which is (and I know people will disagree with this, but I’m over-simplifying for the sake of brevity) probably the only realistic alternative to AngularJS at the moment.

React, on the other hand, promotes a way of separating and organising display and application logic that just seems to make natural sense to me — that’s just how my thought processes work, other people will disagree and find AngularJS a more natural fit, that’s fine.

So this is the first in a series of posts in which I take a voyage of discovery into a world which I hope will end up with me understanding a whole heap of new things, including (but not limited to) React, Redux, React Router, Webpack and no doubt many more…

Development environment

Before we do anything else, we need to set up a development environment.

How things used to work

Back in the “good old days” (i.e. anything more than about two or three years ago), you could quickstart a JavaScript project with an absolute minimum of effort. All you’d need to do is create a folder, and add a couple of files:

index.html

<!doctype html>
<html>
<head>
<title>My JavaScript Project</title>
<script src="app.js"></script>
</head>
<body>
<div id="app-container">
</div>
</body>
</html>

app.js

document.getElementById('app-container').innerHTML = 'Hello World';

And then you just open index.html in your favourite browser and Hey presto! you’ve built your first dynamic website. So your “development environment” extended to your preferred code editor, and a browser, and that’s all.

How things work now

Things are, alas, not quite so straightforward now. Our original example worked because it didn’t rely on any external libraries or tools — just the JavaScript engine built into every web browser.

Once we start wanting to play with React — which we do, because otherwise we’d be off reading something more interesting — things get a bit more complex.

Let’s recreate our vanilla HTML-and-JavaScript example in React:

index.html

<!doctype html>
<html>
<head>
<title>My React Project</title>
</head>
<body>
<div id="react-container">
</div>
<script src="app.js"></script>
</body>
</html>

app.js

var React = require('react');
var ReactDOM = require('react-dom');
var Hello = React.createClass({
render: function () {
return <div>Hello {this.props.name}</div>;
}
});
ReactDOM.render(
<Hello name="World" />,
document.getElementById('react-container')
);

Now let’s run that and see what happens. Erm, it doesn’t work.

For starters, React isn’t supported out-of-the-box by browsers, so we need to somehow import the React library into our project. That’s easy enough — for simple examples we can just include in via a <script> tag:

<script src="https://unpkg.com/react@15.3.1/dist/react.js"></script> <script src="https://unpkg.com/react-dom@15.3.1/dist/react-dom.js"></script>

But we also need to add support for React’s JSX format — which is allows you to write your components in a syntax which merges HTML and JavaScript — because at the moment browsers will take one look at this code and throw syntax errors. This makes things a bit more tricky…

Creating our development environment

There are lots of “starter kits” you can clone from GitHub which will help set up a development environment that solves these things for you, but how do you choose which one is right for you? If, like me, you’re just starting with React, there’s no way yet of knowing which one is best going to suit your current and future needs, and indeed your preferred style of coding and organising projects.

So for the moment, we’re going to take a more bare-bones approach, and learn some the hard way how to do some of the things that these starter kits solve — this, to my mind at least, is a better way of working than starting off with a kit that does all sorts of things that you don’t quite know in a way that you don’t quite understand. In the long run it’s probably better to endure a bit of the pain first, and then make a more informed decision about the best set of tools to avoid that pain for future projects…

So the rest of this post is going to be dedicated to creating the absolute minimum environment that will make our first React example (see above) actually work.

Node.js

First up, we’ll need to install Node.js, which is a server-side JavaScript engine — so basically it does the same job as PHP or ASP.NET or whatever-your-favourite-web-application-platform-is, but it means you don’t have to learn another language. We’re not actually going to be using its web serving capabilities much, but we will be using lots of Node modules from the command line to do useful things like turn JSX into something our browser can actually understand.

Go to the Node.js website — https://nodejs.org — and download the latest LTS version of Node for your operating system — if you get stuck — well, just Google “how to install node” and I’m sure you’ll find some help!

Creating package.json

Node projects use a file called package.json to describe their dependencies (other packages that the project uses) and also to configure the project and optionally its dependent modules. In a nutshell, this means that rather than distributing the project and all of its dependent modules (which, even on a modestly-sized project, can amount to tens or even hundreds of megabytes of code), you just distribute package.json and then use the Node package manager — npm for short — to install any dependencies.

Assuming you’ve got Node installed correctly, make yourself a folder for the new project we’re going to create, and in that folder, open up a command prompt and run the following:

npm init

This will ask you a series of questions about the project you’re creating — for the moment, we don’t need to worry about these, and can just accept the default by hitting “enter” after each question, and then typing “yes” at the end when it asks “Is this ok?”

If all goes according to plan, you’ll end up with a package.json file that looks something like this:

{
"name": "react-basics",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"description": ""
}

(The “name” field is taken from the folder name, so this might well be different for you, depending on what you’ve called your project folder.)

Project structure

We’re about to introduce some steps that take code that your browser doesn’t understand (e.g. React code include JSX) into code that it does understand, so to keep these separate, let’s split our project into “source” — files before converstion — and “build” — files which can be rendered by the browser.

If you’ve still got the non-working React versions of index.html and app.js from above, then move index.html into the build folder, and app.js into the source folder.

Installing React

Now we’re going to install React — although we could just include it via a <script> tag, ultimately we’re going to add several other modules and have a “build” system that sticks them all together, which means we’re better off adding React as a Node module.

From the command line, run the following:

npm install --save react react-dom

The “save” bit tells the Node package manager to save the fact that we have installed these two modules in the “depedencies” section in our package.json file.

Installing Gulp

Next we’re going to install Gulp, which is a “task runner” or “build tool” which we’ll use to simplify the process of transforming React code into something the browser can execute, combining our various source files, and in due course lots of other cool and groovy (and, more importantly, time-consuming) tasks.

First we’ll install it “locally” (i.e. as part of our project), using the “save-dev” flag which marks it as a module that the project needs during development, but not when the finished project is run:

npm install --save-dev gulp

We’ll also install gulp “globally” so that we can run its command-line tools without having to specify a path:

npm install --global gulp

Gulpfile

The next step is to create a Gulpfile, which (as you’ve probably guessed) is a file which tells Gulp what to do and how to work. Gulp is based around the concept of “tasks”, which are commands that typically operate on a set of files and execute one or more processes on those files.

In this case (and don’t worry too much about the details for now, all of these things will become clearer in future posts), we’re going to take our application source file, convert it into a browser-compatible form (at the moment it’s using Node-style “require” commands to access external libraries), convert the JSX into browser-compatible code, then bundle up our source file and any other dependencies — principally, React itself — and spit out a single JavaScript file that contains our “compiled” application.

So fire up a code editor and create gulpfile.js in the root of your project folder:

var gulp = require('gulp');var browserify = require('browserify'),
babelify = require('babelify'),
source = require('vinyl-source-stream');
gulp.task('default', function () {
return browserify('./source/app.js')
.transform(babelify)
.bundle()
.pipe(source('app.js'))
.pipe(gulp.dest('./build/'));
});

Once again, don’t worry if this isn’t all clear yet — once you’ve tinkered for a little while, lots of these steps will make a lot more sense. But in a nutshell, what we’ve done is create a task called “default” which transforms our non-executable React code into something a browser can run.

Gulp dependencies

As you’ll see above, our Gulpfile requires three additional libraries, so let’s add these now:

npm install --save-dev browserify babelify vinyl-source-stream

Babel configuration

We’ll also need to do a little bit of work to configure Babel, which converts React code (and ES6 JavaScript, if you fancy writing your code using the additional JavaScript language features that ES6 provides — we don’t need any of these yet, but at some point in the not-too-distant future it will probably be sensible to make the leap).

Firstly, we need an additional couple of modules to make Babel work with React and ES6 code:

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

And then we need to manually edit our package.json and insert the following (anywhere will do, as long as the JSON remains syntactically correct, i.e. make sure you stick commas in the right place):

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

Build time

And that’s the boring bits out of the way. We should now be able to generate our finished application as follows:

gulp

If all goes according to plan, you’ll see app.js appear in the build folder — it will be huge, despite the tiny amount of code we’ve written, because (as you’ll know from above) it contains the combination of our app code and all its dependencies, which includes the React library.

But more importantly, you’ll now be able to open build/index.html in a browser, and see it work!

Of course it’s a massive disappointment, because all it does is say “Hello World” despite all of the work you’ve just done… but the key thing is that you now have the tools in place to be able to experiment with React code — edit your source/app.js file, run gulp from the command line, and refresh your browser to see your updated code in action.

Magic! Not that there isn’t plenty of room for improvement, but you’re now in a position to write simple React code and see it in action.

Tune in next week…

In the next part of what will hopefully be a continuing series, we’ll extend this rather minimal setup and add things like automatic recompilation, error notifications, a local web server, and live reload functionality…

--

--

Andy Neale

Web developer. Currently building web apps in React. Also known to use Node, jQuery, Foundation and more. Frequently covered in cats.