Joseph Jude

Understanding routing in React.js

2018.03.27 / code / react /

Learn fundamentals of React-router v4

Every web application is in need of navigating between its pages. React doesn’t come with its own routing library. But React community has built many routing libraries, React Router being the most popular. In this article, we will build a simple React application using React router.

Here is what we will build:

React Router

The homepage links to two other pages, capitals and currencies, and each of these pages link to home and the other page.

This is in continuation to the earlier article—Rendering an array of data with React.js. We will use similar arrays of data to display capitals and currencies.

Let us start with creating a React app.

For this we will use the standard create-react-app command. In your terminal issue this command: npx create-react-app router. This will create a new react app in a folder router. You can go into the folder and start the development server with npm start. It will start the server and open the application in the default browser.

Let us install react-router. React router has a library for web apps and mobile apps. We need the web-library react-router-dom. Install it:

npm install --save react-router-dom

Since we have installed all the necessary modules, let us start coding our routing application.

Our navigation sequence goes like this:

Let us start with the Home component. As you see in the screenshot, the home screen contains three links — Home, Capitals, and Currencies. In HTML, they will all be anchor tags with a href linking to the pages. If we use anchor tags, it will cause the whole page to refresh, which is not what we want. React Router has a Link component for this purpose. As its name says, it links to pages within the application. Link component is the simplest component of the Router library.

Our Home is a functional stateless component. It uses Link component to link to other pages (which we are yet to code). Code for Home component looks like this:

import React from "react";
import { Link } from "react-router-dom";

const Home = () => (
  <div>
    <ul>
      <li>
        <Link to="/">Home</Link>
      </li>
      <li>
        <Link to="/capitals">Capitals</Link>
      </li>
      <li>
        <Link to="/currencies">Currencies</Link>
      </li>
    </ul>
  </div>
);

export default Home;

Currency and Capital components are copied from the earlier article, Rendering an array of data with React.js, with just one change. There is a Link component at the end of these components.

import React from "react";
import { Link } from "react-router-dom";

class Currencies extends React.Component {
  render() {
    let countries = [
      { name: "India", currency: "Rupee" },
      { name: "Belgium", currency: "Euro" },
      { name: "America", currency: "Dollar" }
    ];

    return (
      <div>
        <ul>
          {countries.map(country => (
            <li>
              Currency of {country.name} is {country.currency};
            </li>
          ))}
        </ul>
        <p>
          <Link to="/">Home</Link> / <Link to="/capitals">Capitals</Link>
        </p>
      </div>
    );
  }
}

export default Currencies;

We will also code a NotFound.js, which will just display a not found message for non-existing url links. It is also a functional component.

import React from "react";

const notFound = () => (
  <div>
    <h2>Not Found</h2>
  </div>
);

export default notFound;

We have coded all the necessary components. We have to wire them together with Route component. Here are the relevant properties of Route component:

Router has a Switch component that goes through list of paths and render the first path that matches. We use Switch, because if none of the paths matches we want to display the NotFound component.

Since this is a web application, we will use BrowserRotuer component. It makes uses of HTML5 history API, so that when you navigate the history is pushed into the browser history. You can click back and forward buttons of the browser to navigate.

Here is the Routes.js code:

import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import Home from "./Home";
import NotFound from "./NotFound";
import Capitals from "./Capitals";
import Currencies from "./Currencies";

const Router = () => (
  <BrowserRouter>
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/capitals" component={Capitals} />
      <Route path="/currencies" component={Currencies} />
      <Route component={NotFound} />
    </Switch>
  </BrowserRouter>
);

export default Router;

We can render these routes directly in index.js rather than the default App component. Modify index.js like this:

import React from "react";
import ReactDOM from "react-dom";
import Routes from "./components/Routes";

ReactDOM.render(<Routes />, document.getElementById("root"));

If you have the developer server running, the app will automatically update itself. Otherwise, you can see the result by starting the development server with the command npm start.


Share this post on

Twitter | | |
Sign up for my weekly newsletter

I will send blog updates to this email. You can unsubscribe at any time using the link in those emails.