Reader small image

You're reading from  React Router Quick Start Guide

Product typeBook
Published inSep 2018
Reading LevelIntermediate
PublisherPackt
ISBN-139781789532555
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Sagar Ganatra
Sagar Ganatra
author image
Sagar Ganatra

Sagar Ganatra is a frontend engineer and an architect from Bangalore, India. He has more than a decade of experience in developing web and mobile applications. He specializes in architecting projects using JavaScript and frameworks such as React, Angular, and Node. His previous books include Kendo UI Cookbook and Instant Kendo UI Mobile, both published by Packt Publishing. He also writes about frontend technologies in his blog, sagarganatra (dot) com.
Read more about Sagar Ganatra

Right arrow

Using StaticRouter in a Server-Side Rendered React Application

Server-Side Rendering (SSR) is a technique of rendering client-side only single-page applications (SPAs) on the server and sending the fully rendered page as a response to the user's request. In client-side SPAs, the JavaScript bundle is included as a script tag, and, initially, no content is rendered in the page. The bundle is first downloaded, and then the DOM nodes are populated by executing the code in the bundle. There are two downsides to this—on poor connections, it might take more time to download the bundle, and the crawlers that don't execute JavaScript will not be able to see any content, thus affecting the page's SEO.

SSR solves these problems by loading HTML, CSS, and JavaScript in response to the user's request; the content is rendered on the server and the final HTML is given...

Performing SSR of a React application using Node.js and Express.js

In this example, we will use Node.js and Express.js to create a server-side application that will render the React application on the server. Node.js is a cross-platform JavaScript runtime environment for servers and applications. It is built on Google's V8 JavaScript engine, and it uses an event-driven, non-blocking I/O model, which makes it efficient and lightweight. Express.js is one of the most popular routing and middleware web-framework modules used in the Node.js environment. It allows you to create middleware that helps with handling HTTP requests from clients.

Installing dependencies

Let's first create a server-side application using the...

Adding <StaticRouter> and creating routes

The <StaticRouter> component is part of the react-router-dom package (uses <StaticRouter> definition in react-router), and it's used in rendering React-Router components on the server-side. The <StaticRouter> component is similar to the other Router components, as it accepts only one child component—the React application's root component (<App />). This component should be used in a stateless application, where the user is not clicking around to navigate to different sections of the page.

Let's include the <StaticRouter> component by wrapping the application's root component:

import { StaticRouter } from 'react-router-dom';

app.get('*', (req, res) => {
const context = {};
const reactMarkup = ReactDOMServer.renderToString(
<StaticRouter...

StaticRouter context prop

The <StaticRouter> component accepts props basename, location, and context. Similar to other Router implementations, the basename prop in <StaticRouter> is used to specify the baseURL location and the location, prop is used to specify the location properties—pathname, hash, search, and state.

The context prop is used only in the <StaticRouter> implementation, and it contains the result of the component render. As mentioned previously, the context object can be populated with an HTTP status code and with other arbitrary properties as well.

At the time of initialization, the context object can contain properties that can then be consumed by the rendered component:

const context = {
message: 'From StaticRouter\'s context object'
}

const reactMarkup = ReactDOMServer.renderToString(
<StaticRouter context={context...

Creating Isomorphic React applications

An application where the code can run on server-and client-side environments with little or no change is referred to as an Isomorphic application. In an Isomorphic application, the first request made by the user's web browser is processed by the server, and any subsequent request is processed by the client. By processing and rendering the first request on the server-side, and sending HTML, CSS, and JavaScript code provides a better user experience, and also helps search engine crawlers to index the page. All subsequent requests can then be processed by the client-side code, which is sent as part of the first response from the server.

Here's the updated request-response flow:

To render the application on the client-side, either of the <BrowserRouter> or <HashRouter> components can be used. For the purpose of this example...

Summary

In this chapter, we looked at how a React application can be rendered on the server-side (with Node.js and Express.js) using the ReactDOMserver.renderToString method. The <StaticRouter> component in React-Router can be used to wrap the application's root component, thus enabling you to add <Route> components that match the requested URL path on the server-side. The <StaticRouter> component accepts props context and location. The staticContext prop (available only on the server-side) in the rendered component contains the data provided by the <StaticRouter> in the context prop. It can also be used to add properties when you want to redirect the user using the <Redirect> component.

The matchPath function is used to determine whether the requested URL matches the provided object of the shape {path, exact, strict, sensitive}. It's similar...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React Router Quick Start Guide
Published in: Sep 2018Publisher: PacktISBN-13: 9781789532555
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
Sagar Ganatra

Sagar Ganatra is a frontend engineer and an architect from Bangalore, India. He has more than a decade of experience in developing web and mobile applications. He specializes in architecting projects using JavaScript and frameworks such as React, Angular, and Node. His previous books include Kendo UI Cookbook and Instant Kendo UI Mobile, both published by Packt Publishing. He also writes about frontend technologies in his blog, sagarganatra (dot) com.
Read more about Sagar Ganatra