Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
React Router Quick Start Guide
React Router Quick Start Guide

React Router Quick Start Guide: Routing in React applications made easy

eBook
€13.98 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

React Router Quick Start Guide

Introduction to React Router 4 and Creating Your First Route

Single page applications (SPAs) have become the de facto standard for developing applications for the web. Many JavaScript libraries and frameworks have emerged that help frontend engineers in developing SPAs. These include React, Angular, Ember, and Backbone, to name a few. These libraries or frameworks abstract native APIs and provide services and components that can be used to build applications quicker. SPAs are an excellent choice for providing a fluid user experience; as the user traverses through the site, HTTP requests are triggered, and only certain sections of the page are updated, instead of requesting the server for the entire page.

React is an open source JavaScript library that helps you in building user interfaces and the view layer in web and mobile applications. It encourages developers to visualize the view layer as a collection of components that can be reused throughout the application. Most frontend frameworks include a routing package that enables you to update sections of the page when the user clicks through various links provided on the site. A router in a frontend framework listens to the changes in the URL and keeps the application in sync by rendering the corresponding view components. For example, when the user visits '/dashboard', the page would render various dashboard components, such as charts and tables, and when the user visits, say, '/user', the page would list various user attributes. In a React-based application, a Router library is required, since React does not ship with one. React-Router is one such popular routing library built completely with React. The library includes various components that can be used to render views as the user navigates through the application. Apart from matching the URL and rendering the view components, React-Router has several features that help you to configure the routes easily.

In this chapter, the following topics are discussed:

  • A brief look at React: This section introduces you to some of the core concepts in React, such as component-based architecture, creating components in React, and how data can be provided to child components in the application tree
  • Introduction to React-Router: Here, we first create a React application using the create-react-app CLI and then add the React-Router library (the 'react-router-dom' package) as a dependency
  • Creating your first route: After adding React-Router as a dependency, the application's first route is created using the <BrowserRouter> and <Route> components

A brief look at React

React is a JavaScript library that provides a set of components and services and enables you to build user interfaces.

Here is a quote from reactjs.org:

"React is a declarative, efficient, and flexible JavaScript library for building user interfaces."

The library is developed and maintained by Facebook and is licensed under MIT. It's extensively used in building various applications at Facebook, including Facebook web and Instagram web.

React enables you to build view components that get updated when the application's state changes. The state here could refer to the underlying domain data, or it may reflect where the user is in the application journey. React ensures that the view components reflect the application state.

Here are some of the important features of React:

  • JSX: Components in React applications use an XML/HTML-like syntax, known as JSX, to render the view elements. JSX allows you to include HTML in your JavaScript/React code; the familiar syntax of HTML with attributes in your React component's render function does not require you to learn a new templating language. This JSX is then used by preprocessors such as Babel to transpile HTML text to JavaScript objects that the JavaScript engine can understand.
  • One-way data binding: React applications are organized as a series of nested components; a set of immutable values are passed to the component's renderer as properties in HTML tags. The component does not modify the properties (or props) it receives from its parent; instead, the child communicates the user actions to its parent component and the parent component modifies these properties by updating the component's state.
  • Virtual DOM: In React, for every DOM object, a corresponding virtual DOM object is created that has the same set of properties as the real DOM object. However, the virtual DOM object lacks the power to update the view when the user interacts with the page. Components in React re-render the view elements whenever a change in state is detected, and this re-render updates the virtual DOM tree. React then compares this virtual DOM tree with the snapshot that was created before the update to determine the DOM objects that changed. Finally, React modifies the real DOM by updating only those DOM objects that changed.

Component-based architecture in React

Since its release in 2013, React has redefined the way that frontend applications should be built. It introduces the concept of component-based architecture, which, in essence, allows you to visualize your application as if it were made up of tiny, self-sustained view components. These view components are reusable; that is, a component such as CommentBox or Footer encapsulates the necessary functionality and can be used across the pages in the site.

A page in this context is itself a view component that is composed of other tiny view components, as shown here:

<Dashboard>
<Header>
<Brand />
</Header>
<SideNav>
<NavLink key=”1”>
<NavLink key=”2”>
</SideNav>
<ContentArea>
<Chart>
<Grid data="stockPriceList">
</ContentArea>
<Footer />
</Dashboard>

Here, <Dashboard> is a view component that encompasses several other view components (Header, SideNav, ContentArea, and Footer), which in turn are made up tiny components (Brand, NavLink, Chart, and Grid). The component-based architecture encourages you to build components that provide certain functionality and are not tightly coupled with any of their parent or sibling components. These components implement certain functionality and provide an interface through which they can be included in the page.

In the preceding example, a <Grid> component would include features such as rendering data in rows and columns, providing search functionality, and also an option to sort the columns either in ascending or descending order. The <Grid> component would implement all of the aforementioned features and provide an interface through which it can be included in the page. The interface here would include the tag name (Grid) and set of properties (props) that accept the values from its parent component. Here, the <Grid> component could interface with the backend system and retrieve the data; however, this would make the component tied tightly to the given backend interface, thus not making it reusable. Ideally, a view component would receive data from its parent component and act accordingly:

<Grid data="stockPriceList" />

Here, the <Grid> component receives a list containing stock price information through its data prop and would render this information in a tabular format. A component that includes this <Grid> component can be termed a Container component and Grid as a child component.

A Container component is also a View component; however, its responsibility includes providing its child components with the necessary data to render. A Container component could initiate HTTP calls to a backend service and receive the data required to render its child components. In addition to that, the Container component is also responsible for the positioning of the individual view components in its view area.

Creating a React component

A React component is created by extending the Component class provided by React as follows:

import React, { Component } from 'react';
import './button.css';

export class Button extends Component {
render() {
return (
<button className={this.props.type}>
{this.props.children}
</button>
);
}
}

Here, the Button class extends React's Component class and overrides the render method. The render method returns the JSX, which will be rendered on the DOM when the page loads. The type and children properties are available in this.props. React allows you to pass data to its components through props and does so by using the following syntax:

import React, { Component } from 'react';
import { Button } from './components/Button/button';
import './App.css';

export default class App extends Component {
render() {
return (
<div className="App">
<Button type="secondary">CANCEL</Button>
<Button type="primary">OK</Button>
</div>
);
}
}

Here, we have wrapped the Button component inside a parent component, App, to render two button elements. The type attribute is consumed by the Button component to set the class name (className) of the CANCEL and OK buttons and text mentioned inside the Button tag. This can be referenced using the children property. The children property can be plain text or other view components. The child component gets a reference to the data provided by its parent component using this.props. The children property in 'this.props' provides a reference to all the child elements included between the tags by the parent component. If you've used Angular in the past, consider the preceding snippet as similar to how you would include elements using ng-transclude in AngularJS, or ng-content in Angular.

Here, the <App> component contains the <Button> component and can be referred to as a container component, which is responsible for rendering the buttons on the page.

The next step is to render the <App> component on the DOM. The <App> component serves as a root component, that is, a root node in a tree. Every component in the application has the <App> component as its top-most parent component:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(<App />, document.getElementById('root'));

This code is included in index.js, which imports the React and ReactDOM libraries. The ReactDOM library has a render method, which accepts the component to be rendered as its first parameter, and a reference to the DOM node where the root component has to be rendered.

When the app is run, the content inside the <App> component is rendered:

Introduction to React-Router

React-Router is a routing library for SPAs built with React. React-Router version 4 is a complete rewrite and embraces the React philosophy of component-based architecture.

This is from the React-Router documentation (https://reacttraining.com/react-router/)

"React Router is a collection of navigational components that compose declaratively with your application. Whether you want to have bookmarkable URLs for your web app or a composable way to navigate in React Native, React Router works wherever React is rendering--so take your pick!"

React-Router can be used wherever React can be applied; that is, React-Router works both in the browser and in the native environment with React Native.

The library is divided into three packages:

  • react-router: Common core components for DOM and Native versions
  • react-router-dom: Components for use in browser and web applications
  • react-router-native: Components for use in native applications built with React Native

The library provides various components that can be used to add routes dynamically to your application. The dynamic routing in React-Router v4 allows you to specify application routes as the user progresses through the application journey. Frameworks such as AngularJS and Express require you to specify the routes upfront, and this routing information is required when the application bootstraps. In fact, the earlier versions of React-Router followed the same paradigm and required the routing configuration to be available upfront.

Apart from dynamic routing and providing fluid navigation in a React application, the library includes various features that are available in traditional websites. These include the following:

  • Navigating backward and forward through the application, maintaining the history, and restoring the state of the application
  • Rendering appropriate page components when presented with a URL (deep-linking)
  • Redirecting the user from one route to the other
  • Support for rendering a 404 page when none of the routes match the URL
  • Support for hash-based routes and pretty URLs with HTML5 mode
It's a common misconception that React-Router is the official routing solution provided by Facebook. In reality, it's a third-party library and is licensed under MIT.

Getting started with React-Router

Let's create a React application and then add React-Router as a dependency.

To create a React application, we will use the create-react-app CLI. The create-react-app CLI makes it easier to create an application that already works. The CLI creates a project scaffold so that you can start using the latest JavaScript features, and also provides scripts to build applications for a production environment. There are various React and React-Router starter kits available; however, using create-react-app helps in demonstrating how React-Router can be added to an existing bare-bones React application.

The first step is to install create-react-app globally using NPM, as follows:

npm install -g create-react-app

The CLI requires the node version to be greater than or equal to 6, and the npm version to be greater than 5.2.0.

Once the CLI has been installed, we will create a new application using the create-react-app command, as seen here:

create-react-app react-router-demo-app

The following output is displayed when create-react-app completes the installation of packages:

Inside that directory, you can run several commands:
npm start
Starts the development server.

npm run build
Bundles the app into static files for production.

npm test
Starts the test runner.

npm run eject
Removes this tool and copies build dependencies, configuration
files
and scripts into the app directory. If you do this, you can't
go back!
We suggest that you begin by typing:
cd react-router-demo-app
npm start

If you used the yarn package manager (https://yarnpkg.com/en/), the npm commands in the preceding snippet would be replaced with yarn.

The react-router-demo-app directory is created during installation (if it doesn't already exist). Inside the directory, the following project structure is created:

/react-router-demo-app
|--node_modules
|--public
| |--favicon.ico
| |--index.html
| |--manifest.json
|--src
| |--App.css
| |--App.js
| |--App.test.js
| |--index.css
| |--index.js
| |--logo.svg
| |--registerServiceWorker.js
|--package-lock.json
|--package.json
|--README.md

The CLI installs all the necessary dependencies, such as Babel, to transpile ES6 code to ES5, thus enabling you to leverage the latest JavaScript features. It also creates a build pipeline configuration with the help of webpack. Post-installation, no additional configuration is required to start or build the app. As noted in the preceding output, you can start the app using the npm start command and build a production-ready app using npm build.

On running npm start, the application is compiled and will open a browser window with a Welcome to React message displayed, as shown here:

In the index.js file, the ReactDOM reference is used to render the application's root component as follows:

ReactDOM.render(<App />, document.getElementById('root'));

The <App> component marks the beginning of the tree that will get rendered when the application starts.

Adding the React-Router library

Now that we have our sample application up and running, let's add React-Router library as a dependency using npm:

npm install --save react-router-dom

This command will download and add react-router-dom to the /node_modules directory. The package.json file now includes this as a dependency:

"dependencies": {
"react": "^16.4.0",
"react-dom": "^16.4.0",
"react-router-dom": "^4.3.0",
"react-scripts": "1.1.4"
}
At the time of writing this book, version 4.3.0 of react-router-dom was available. You can try the alpha and beta builds by mentioning react-router-dom@next when including the library using npm.

Defining application routes

The react-router-dom package includes a <BrowserRouter> component, which is used as a wrapper before adding routes in the application. To use React-Router in the React Native application, the react-router-native package is used. This will be discussed in detail in later chapters. The <BrowserRouter> component is an implementation of the router interface that makes use of HTML5's history API to keep the UI in sync with the URL path.

The first step is to wrap the application's root component with <BrowserRouter>, as shown here:

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

ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);

Wrapping your application inside <BrowserRouter> will create an instance of history for our <App> component, giving all of its child components access to props from the native browser history API. This allows components to match against URL paths and render the appropriate page component.

History is a JavaScript library that lets you manage history stack navigation and helps in persisting state between sessions.

Routing in React-Router isn't actually routing—it's conditional rendering of components based on the pattern that matches with the current URL path. To define a route, we need two pieces of information: the URL path to match with and the component to render. Let's create two components, HomeComponent and DashboardComponent, that render at /home and /dashboard respectively.

In src/components/home/home.component.js:

import React from 'react';

export const HomeComponent = () => (
<div>
Inside Home route
</div>
);

And in src/components/dashboard/dashboard.component.js:

import React from 'react';

export const DashboardComponent = () => (
<div className="dashboard">
Inside Dashboard route
</div>
);

The import statement is required since we are returning JSX from the preceding components.

The next step is to define a route using the Route component (from 'react-router-dom'). The Route component accepts several props, but for the purpose of this example, we will use path and component.

In App.js:

class App extends Component {
render() {
return (
<div className="container">
<Route
path="/home"
component={HomeComponent}
/>
<Route
path="/dashboard"
component={DashboardComponent}
/>
</div>
);
}
}

export default App;

Here, we're defining routes within the 'render' method of the <App> component. Each <Route> component has a path prop, which mentions the URL path to match, and a component prop, mentioning the component to render once the path matches the URL.

In the preceding example, the component was created without extending React's component class. If a component, created by extending React's component class, is provided as a value to the component prop, then the component's lifecycle methods, componentWillMount and componentWillUnmount, are called every time that <Route> renders the component.

When you run the app (npm start) and visit localhost:3000/home, HomeComponent is rendered and the message Inside Home Component is displayed. Similarly, DashboardComponent is rendered when you visit localhost:3000/dashboard.

<BrowserRouter> creates a History object, which it uses to keep track of the current location and re-render the site whenever it changes. <BrowserRouter> makes the History object available to its descendent child components through React's context. A Route component that does not have <BrowserRouter> as its parent will fail to work.

Also, it's a requirement that <BrowserRouter> has only one child element. In the following snippet, <BrowserRouter> is given two child elements:

<BrowserRouter>
<Route
path="/home"
component={HomeComponent} />
<Route
path="/dashboard"
component={DashboardComponent} />
</BrowserRouter>

The preceding code will result in an error, such as A <Router> may have only one child element. To resolve this, you could either move these routes into a component and provide the component reference, or wrap the <Route> components in the preceding snippet inside another element, such as div or React Fragment.

A React fragment is used to group a list of children without adding extra nodes to the DOM. A fragment is used when the component returns multiple elements.

Apart from BrowserRouter, there are other types of routers in the React-Router library: HashRouter, MemoryRouter, and StaticRouter. These are discussed in later chapters.

Summary

React is a JavaScript library used to build user interfaces. Unlike libraries such as Angular and Ember, which include a routing package, the React library does not include any components or services that help in routing. React-Router is a routing library that can be used in any React application, web or native. React-Router version 4 is a complete rewrite of the earlier versions and all of its components are written in React. The library includes the packages react-router-dom for use in web applications; react-router-native, for use in native applications built with React-Native; and react-router, a core package that both react-router-dom and react-router-native have a dependency on.

The create-react-app CLI is used to quickly scaffold a React application. It includes build configuration scripts that can be used to generate builds for development and production environments. The react-router-dom package is then added as a dependency to the application. The package includes the <BrowserRouter> component, which implements a History interface. The application's root component, <App />, is wrapped inside React-Router's <BrowserRouter> component to make the History object available to all the components in the application tree.

To create our first route, the <Route> component is included. It accepts path and component as props, and renders the component when the browser's URL matches the <Route> path.

In Chapter 2, Configuring Routes - Using Various Options in the Route Component, the <Route> component props are discussed in detail. Also, we will take a look at the various props that the rendered component receives, and consider how these props can be used to create nested routes.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Create nested routes and complex workflows for your applications
  • Learn Routing in server-side rendered applications and in Native mobile applications
  • Understand how Redux bindings for React-Router works using the connected-react-router library

Description

React Router is the routing library for React, and it can be used in both React Web and React Native applications. This book is a simple way to get started with React Router and harness its full power for your applications. The book starts with an introduction to React Router and teaches you how to create your first route using the React component. You will then learn about configuring your routes, passing parameters, and creating nested routes. You will be introduced to various components in React-Router and learn different configuration options available for these components. You will then see how to use the Redirect and Switch components. For even greater ?exibility, you will learn about BrowserRouter, HashRouter, NativeRouter, and StaticRouter. By the end of the book, you will have set up a project with React Router and make routing configuration work in a server-side rendered React application, a mobile application built with React Native and also understand how Redux and React-Router can be used in the same application.

Who is this book for?

This book is for JavaScript developers who have basic knowledge of React and who want to harness the power and flexibility of React Router

What you will learn

  • Create your first Route using the Route component
  • Protect routes from unauthorized access by using the redirect component
  • Navigate to your defined route using Link and NavLink
  • Configure BrowserRouter and HashRouter using various props
  • Use StaticRouter for routing in server-side rendered React applications
  • Implement routing in a React Native app using react-router-native
  • Using connected-react-router library with React-Router for better state management

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 29, 2018
Length: 156 pages
Edition : 1st
Language : English
ISBN-13 : 9781789532838
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Sep 29, 2018
Length: 156 pages
Edition : 1st
Language : English
ISBN-13 : 9781789532838
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 98.97
React Cookbook
€36.99
Learn React with TypeScript 3
€36.99
React Router Quick Start Guide
€24.99
Total 98.97 Stars icon
Banner background image

Table of Contents

9 Chapters
Introduction to React Router 4 and Creating Your First Route Chevron down icon Chevron up icon
Configuring Routes - Using Various Options in the Route Component Chevron down icon Chevron up icon
Using the Link and NavLink Components to Navigate to a Route Chevron down icon Chevron up icon
Using the Redirect and Switch Components Chevron down icon Chevron up icon
Understanding the Core Router, and Configuring the BrowserRouter and HashRouter components Chevron down icon Chevron up icon
Using StaticRouter in a Server-Side Rendered React Application Chevron down icon Chevron up icon
Using NativeRouter in a React Native Application Chevron down icon Chevron up icon
Redux Bindings with connected-react-router Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.