Reader small image

You're reading from  React Components

Product typeBook
Published inApr 2016
Publisher
ISBN-139781785889288
Edition1st Edition
Tools
Right arrow
Author (1)
Christopher Pitt
Christopher Pitt
author image
Christopher Pitt

Christopher Pitt is a principal developer for SilverStripe in Wellington, New Zealand. He usually works on open source software, though sometimes you'll find him building compilers and robots.
Read more about Christopher Pitt

Right arrow

Chapter 7. Rendering on the Server

In the last chapter, you learned how to render different sections of our CMS without reloading the page. We even created a way to see the public pages of our website, using the same routing techniques.

So far, we did everything in the browser. We stored pages in local storage. We used the website and CMS as if they were hosted on the Internet, but we're the only ones who can see it. If we want to share our creations with others, we need some kind of server-side technology.

In this chapter, we will take a brief look at some aspects of server-side JavaScript and React programming. We'll see how React works outside of the browser, and how we can persist and share data with many people in real-time.

Rendering components to strings


One of the beautiful things about React is that it works in many places. It is aimed at rendering interfaces efficiently, but those interfaces can extend outside of the DOM and the browser.

You can use React to render native mobile interfaces (https://facebook.github.io/react-native), or even plain HTML strings. This becomes useful when we want to reuse the component code in different places.

We can, for instance, build an intricate data table component for our CMS. We can ship that component to an iPad application or even render it from the web server as a way of minimizing page load time.

It's the latter example that we will try in this chapter. To begin, we need to install the source versions of React and React DOM libraries:

$ npm install --save babel-cli babel-preset-react babel-preset-es2015 react react-dom

We've already seen examples of the React libraries, but these new ones (from BabelJS) will give us a way of using ES6 and JSX on the server. They even...

Creating a simple server


Now that we can render components to HTML strings, it would serve us better to have a way to respond to HTTP requests with HTML responses.

Fortunately, Node.js also includes a neat little HTTP server library. We can use the following code, in the server.js file, to respond to HTTP requests:

var http = require("http");

var server = http.createServer(
    function (request, response) {
        response.writeHead(200, {
            "Content-Type": "text/html"
        });

        response.end(
            require("./hello-world")
        );
    }
);

server.listen(3000, "127.0.0.1");

To use the HTTP server library, we need to require/import it. We create a new server, and in the callback parameter, respond to individual HTTP requests.

For each request, we set a content type and respond with the HTML value of our hello-world.js file. The server listens on port 3000, which means you'll need to open http://127.0.0.1:3000 to see this message.

Before we can do that, we also...

Creating a server backend


One of the things our CMS is still missing is public, persistent pages. So far, we stored them in local storage, and that's OK while we build up our CMS components. But a time will come when we would want to share our data with the world.

For this to work, we need some storage mechanism. Even if that storage is only in memory for as long as the server is running. Sure, we could use a relational database or an object store to persist our CMS pages. For now, let's keep things simple. An in-memory store (pages variable) should do for now.

So, how should we structure this data store? Whatever storage medium we choose, the interface will need to reach out to the server to store and retrieve data. There are two mainstream options I want to explore...

Communicating through Ajax requests


Ajax is a loaded word. For the purposes of this chapter, I want you to think of it only as a means to fetch data from a server and send data to it using HTTP requests.

We've just seen how we can respond to HTTP requests, so we're half-way there! At this point, we can inspect requests to determine the URL and method of each HTTP request. A browser may be requesting something like GET http://127.0.0.1:3000/pages to get all the pages. So, if the method matches POST and the path matches /pages, then we can respond with the appropriate pages.

Luckily for us, others have been down this path before. Projects such as ExpressJS have sprung up to provide some scaffolding for us. Let's install ExpressJS:

$ npm install --save express

Now, we can convert our simple HTTP server to be based on ExpressJS:

var app = require("express")();
var server = require("http").Server(app);

app.get("/", function (request, response) {
    response.send(
        require("./hello-world...

Communicating through web sockets


Sometimes, it's better to have fast, bi-directional communication between the browser and the server.

At such a time, you can try web sockets. They're an upgrade to the traditional HTTP communication seen in Ajax. To work with them easily, we need the help of Socket.IO:

npm install --save socket.io

Now we can access a new object, which we'll call io:

// ...enable JSX/ES6 compilation

var app = require("express")();
var server = require("http").Server(app);
var io = require("socket.io")(server);

app.get("/", function (request, response) {
    response.send(
        require("./hello-world")
    );
});

// ...define other endpoints

io.on("connection", function (socket) {
    console.log("connection");

    socket.on("message", function (message) {
        console.log("message: " + message);

        io.emit("message", message);
    });
});

server.listen(3000);

Note

The "message" can be anything. You can send messages of different types simply by changing this...

Structuring server-side applications


When it comes to HTTP and web socket servers, it's usually a good idea to separate the endpoint code from the server initialization code. Some folks like to create separate routes files, which can then be required by the server.js file. Still others like to have each endpoint as a separate file and define routes as glue between server.js and these "handler" files.

Perhaps that's enough for the kinds of applications you will build, or perhaps you like a more prescriptive structure to your applications, something such as AdonisJS (http://adonisjs.com), for example.

Adonis is a beautifully structured MVC framework for Node.js applications. It uses many cool tricks (such as generators) to enable a clean API for defining templates, request handlers, and database code.

A typical request can be handled in the following way:

class HomeController {
    * indexAction (request, response) {
        response.send("hello world");
    }
}

module.exports = HomeController...

Summary


In this chapter, you learned how to render components on the server. We created a simple HTTP server and then upgraded it to allow multiple endpoints and web sockets. Finally, we looked briefly at how we can structure our server-side code and quickly looked at the AdonisJS MVC framework.

In the next chapter, you will learn about some popular React design patterns that you can apply to your components and interfaces.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React Components
Published in: Apr 2016Publisher: ISBN-13: 9781785889288
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Christopher Pitt

Christopher Pitt is a principal developer for SilverStripe in Wellington, New Zealand. He usually works on open source software, though sometimes you'll find him building compilers and robots.
Read more about Christopher Pitt