This article was originally published on Stormpath. Thank you for supporting the partners who make SitePoint possible.
React (sometimes referred to as React.js) is an awesome way to build web UIs. The Stormpath React SDK extends React and React Router with routes and components that allow you to solve common user management tasks using Stormpath, such as authentication and authorization.
Lately, React has picked up quite some attention, and it's easy to understand why. React allows you to turn complex UIs into simple and reusable components that can be composed easily together.
This post will show you how to build a React application from scratch, using the Stormpath React SDK to add features that allow people to sign up, log in, and even view their own user profile.
Let's get started!
The React + Express.js Application Stack
Since we're building our app from scratch, we'll use ES6 and JSX to write as little code as possible, as well as the Stormpath React SDK for user features.
To give you a good overview of what we'll be using:
- React - Allows us to compose simple yet powerful UIs.
- ReactRouter - Organizes the URL navigation in our React application.
- ES6 - The next version of JavaScript. Allows us to write real JavaScript classes.
- JSX - Allows us to place HTML in JavaScript without concatenating strings.
- Stormpath - Allows us to store and authenticate users without having to create our own backend for it.
- Stormpath React SDK - Integrates registration forms, login pages and authentication into our React application with very little effort.
- Express - Allows us to serve our HTML and JavaScript files.
- Express Stormpath - Allows us to serve Stormpath's API through Express.
- Webpack - Allows us to pack all of our JavaScript files into one bundle.
- Babel - Allows us to transpile our ES6 and JSX into ES5.
- Bootstrap - Because we want things to be pretty.
Setting up Our React + Express.js Project
Start by creating a new project directory and a package.json
file for it.
$ mkdir my-react-app
$ cd my-react-app
$ npm init --yes
Now install Express, the Stormpath module for Express, and Body Parser:
$ npm install --save express express-stormpath body-parser
We need a server to host our application, so create a new file named server.js
and put the code below in it:
var express = require('express');
var stormpath = require('express-stormpath');
var bodyParser = require('body-parser');
var app = express();
app.use(stormpath.init(app, {
web: {
produces: ['application/json']
}
}));
app.on('stormpath.ready', function () {
app.listen(3000, 'localhost', function (err) {
if (err) {
return console.error(err);
}
console.log('Listening at http://localhost:3000');
});
});
Awesome. Now we can hook that up to a Stormpath Application by creating a new file named stormpath.yml
with the following code in it. And yeah, you do have to replace those values in it with your own.
client:
apiKey:
id: YOUR_API_KEY_ID
secret: YOUR_API_KEY_SECRET
application:
href: http://ift.tt/2buVlTO <-- YOUR APP HREF
So far so good. Now try the server by running $ node server.js
. If everything is set up correctly then you should see:
Listening at http://localhost:3000
If you saw that message, you've successfully configured your server to talk with Stormpath and expose a REST API for our React application to use.
Configuring Webpack
Before you get too excited, kill the server and install Webpack so that we can package all of our client-side scripts (we'll need this organization soon).
$ npm install --save webpack
$ npm install --save-dev webpack-dev-middleware
Configure Webpack by creating a new file named webpack.config.js
and put the code below in it:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: [
'./src/app'
],
devtool: 'eval-source-map',
output: {
path: __dirname,
filename: 'app.js',
publicPath: '/js/'
},
module: {
loaders: []
}
};
What this will do is look in our /src/
directory (that we'll create shortly) and package all of the scripts and their dependencies under that directory as one module. Then use the file /src/app.js
and its exports as the export of that module. Then finally when it has generated that module package, it will serve that through Express under the /js/app.js
endpoint.
But in order for Express to serve Webpack files, we have to open up server.js
and add these lines to the top of it:
var webpack = require('webpack');
var config = require('./webpack.config');
Then immediately after the line var app = express();
add:
var compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
As I mentioned before, this will allow Webpack to intercept requests and serve our packaged /js/app.js
file.
Configuring Babel
Since we'll be using ES6 and JSX, we need to transpile these files into ES5 (for backwards compatibility with non-modern browsers). This is where Babel comes in. Babel can take our ES6/JSX files as input, and convert those to ES5.
To use Babel, start by installing some dependencies:
$ npm install --save babel-core babel-runtime babel-loader babel-plugin-react-transform \
babel-preset-es2015 babel-preset-react babel-preset-stage-0
Now we'll instruct Babel on how to compile our files, so create a new file named `.babelrc` and add this code it:
{
"presets": ["stage-0", "es2015", "react"]
}
Finally, in order to get Babel to work with Webpack, we need to edit `webpack.config.js` and add an entry to the `module.loaders` array, as shown below:
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'src')
}]
}
Index.html and Bootstrap
Now, before getting our hands dirty with React, we'll prepare the entry page for our app. This page will tell the browser what it must load before we initialize React and our application. So create a new directory named build
, then within that, put a file named index.html
. Our server will serve all of our static files from this folder.
$ mkdir build
$ cd build
$ touch index.html
Then within index.html
, put the following:
<!doctype html>
<!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7"><![endif]-->
<!--[if IE 7]><html class="no-js lt-ie9 lt-ie8"><![endif]-->
<!--[if IE 8]><html class="no-js lt-ie9"><![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js"><!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<base href="/">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="/css/bootstrap.min.css" />
</head>
<body>
<div id="app-container"></div>
<script src="/js/app.js"></script>
</body>
</html>
Also, under the build
directory, create a new directory named css
and download Bootstrap to it. Name the file bootstrap.min.css
.
$ mkdir css
$ cd css
$ curl -O http://ift.tt/1jAc5cP
$ cd ../.. # return to /my-react-app
Now in order for our browser to be able to access these files we need to configure them so that they are served through Express. So open up server.js
and at the top of the file add:
var path = require('path');
Then under the line app.use(stormpath.init(app, ...));
add:
app.get('/css/bootstrap.min.css', function (req, res) {
res.sendFile(path.join(__dirname, 'build/css/bootstrap.min.css'));
});
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, 'build/index.html'));
});
How Does React Work?
Now that we have the skeleton for our app done, we can focus on building our React app. But before we write any code, let's take a look at what React is and what it does for us.
Components
In React, everything is built upon components. You can think of a component as something that renders a DOM node. A simple React component looks like this:
class HelloWorld extends React.Component {
render() {
return <span>Hello World!</span>;
}
}
That was simple. Now, if you wanted to render this component to a page, then all you'd have to do is import React and then call:
ReactDOM.render(
<HelloWorld />,
document.getElementById('hello-world-element')
);
And React would render the component to that element.
There are, of course, more things to a React component, such as state. Below is an example of a counter component that starts counting when added to the DOM and stops when removed.
class Counter extends React.Component {
state = {
current: 0
}
constructor() {
super(arguments...);
this.intervalId = null;
}
updateCounter() {
this.setState({ counter: this.state.current + 1 });
}
componentWillMount() {
this.setState({ counter: this.props.from || 0 });
this.intervalId = setInterval(this.updateCounter.bind(this), 1000);
}
componentWillUnmount() {
clearInterval(this.intervalId);
}
render() {
return <span>{ this.state.current }</span>;
}
}
Notice the methods componentWillMount()
and componentWillUnmount()
. These are component life-cycle methods that will be executed at various points of a component's life-cycle (in this case, mount and unmount). These methods are usually used for setting up and tearing down a component and is necessary to use because React will error if you try to set the state of a component when it hasn't been mounted yet.
Also notice this.props.from
. The member this.props
is a collection of all the properties (inputs) passed to a component. Properties of a component can be set as shown below:
<Counter from="50" />
<Counter from={ myVariable } />
JSX Variables
Variables can easily be interpolated into your JSX DOM using { nameOfVariable }
, e.g. as shown below:
render() {
var myVariable = 123;
return <span>{ myVariable }</span>;
}
JSX and Reserved JavaScript Identifiers
Since JSX is JavaScript, there are some caveats that you need to know when working with React. I.e. when setting properties of a React DOM component you cannot use neither for
or class
since those are considered reserved JavaScript identifiers. To get around this problem, React has come up with htmlFor
and className
that you should use instead.
To illustrate the issue, this won't work:
<label for="my-input" class="my-label">My Input</label>
But this will:
<label htmlFor="my-input" className="my-label">My Input</label>
Virtual DOM
Instead of working directly against the DOM, in React all components are kept in their own virtual DOM. You can think of the virtual DOM as a DOM implementation in JavaScript (because it actually is). This virtual DOM is then mapped to a real DOM element. So when you render your React component, React will look at the DOM output from the component, compare it to its representation in the virtual DOM, and then generate a patch for the real DOM.
What this means is that you never have to think of manually manipulating DOM elements again. All you have to do is tell React how you want your component to look like, and it will take care of transforming the DOM the ways necessary (with minimal effort).
Installing React Dependencies
Now when we are acquainted with React, we'll kick things off by installing some React dependencies:
$ npm install --save react react-dom react-router react-stormpath react-document-title history
Before we start coding, we need a place to put our React files, so create a new directory named src
, and then use that as your working directory.
$ mkdir src
$ cd src
Now, let's start with the entry point of our app. This will be the place where we will set up our React application and its routing. So create a new file named app.js
and enter this code:
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, IndexRoute, Route, browserHistory } from 'react-router';
ReactDOM.render(
<Router history={browserHistory}>
</Router>,
document.getElementById('app-container')
);
So now we have a foundation for our application. Let's go ahead and import the Stormpath SDK and some things we'll need in it. At the top of your app.js
file, add the import statement:
import ReactStormpath, { Router, HomeRoute, LoginRoute, AuthenticatedRoute } from 'react-stormpath';
As you can see in app.js
there's now two conflicting Router
imports. Since ReactStormpath.Router
extends from ReactRouter.Router
we won't be needing that anymore. So go ahead and remove the Router
import from react-router
. Important: Leave the other ReactRouter imports, we'll be needing those later.
Now, we'll initialize the Stormpath SDK. Add the following line right above ReactDOM.render()
.
ReactStormpath.init();
That was easy! We're now ready to start building our pages.
Master Page
Before we create our pages, we have to set up our router. The router is what determines how we'll be able to navigate around in our React application. We'll start by creating a shared root route. This will act as our "master page". I.e. all routes under this route will all share the same master component (header). So place the code below inside the <Router>
tag in app.js
so that it looks like this:
<Router history={browserHistory}>
<Route path='/' component={MasterPage}>
</Route>
</Router>
As you can see, we have referenced MasterPage
. Something that doesn't exist yet. So let's go ahead and create that in a new directory that we'll name pages
, in our src
folder.
$ mkdir pages
$ cd pages
Now create a new file named MasterPage.js
and add this code to it:
import React from 'react';
import { Link } from 'react-router';
import { LoginLink } from 'react-stormpath';
import DocumentTitle from 'react-document-title';
import Header from './Header';
export default class is extends React.Component {
render() {
return (
<DocumentTitle title='My React App'>
<div className='MasterPage'>
<Header />
{ this.props.children }
</div>
</DocumentTitle>
);
}
}
As you can see, we don't have a Header
component yet, so let's go and create a new file named Header.js
in the same directory with the following content:
import React from 'react';
import { Link } from 'react-router';
import { LoginLink, LogoutLink, Authenticated, NotAuthenticated } from 'react-stormpath';
export default class Header extends React.Component {
render() {
return (
<nav className="navbar navbar-default navbar-static-top">
<div className="container">
<div id="navbar-collapse" className="collapse navbar-collapse">
<ul className="nav navbar-nav">
<li><Link to="/">Home</Link></li>
</ul>
<ul className="nav navbar-nav navbar-right">
</ul>
</div>
</div>
</nav>
);
}
}
Index Page
In our MasterPage
notice the property this.props.children
. This will contain the components of the child routes that our router match. So if we had a route that looked like:
Continue reading %Build a React.js Application with User Login and Authentication%
by Robin Orheden via SitePoint