Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
React Router Quick Start Guide

You're reading from   React Router Quick Start Guide Routing in React applications made easy

Arrow left icon
Product type Paperback
Published in Sep 2018
Publisher Packt
ISBN-13 9781789532555
Length 156 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Sagar Ganatra Sagar Ganatra
Author Profile Icon Sagar Ganatra
Sagar Ganatra
Arrow right icon
View More author details
Toc

Table of Contents (10) Chapters Close

Preface 1. Introduction to React Router 4 and Creating Your First Route FREE CHAPTER 2. Configuring Routes - Using Various Options in the Route Component 3. Using the Link and NavLink Components to Navigate to a Route 4. Using the Redirect and Switch Components 5. Understanding the Core Router, and Configuring the BrowserRouter and HashRouter components 6. Using StaticRouter in a Server-Side Rendered React Application 7. Using NativeRouter in a React Native Application 8. Redux Bindings with connected-react-router 9. Other Books You May Enjoy

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.

You have been reading a chapter from
React Router Quick Start Guide
Published in: Sep 2018
Publisher: Packt
ISBN-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.
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 $19.99/month. Cancel anytime