loading...
Cover image for React Router Tutorial: Adding Navigation to your React App
Educative

React Router Tutorial: Adding Navigation to your React App

amandaeducative profile image Amanda Fawcett Originally published at educative.io ・8 min read

This article was written by Erin Doherty and was originally published on Educative.io.

In this React tutorial, we'll be taking a look at React router - a specific library for handling routes within a web app. At its core, what React Router does is conditionally render certain components to display depending on the route being used in the URL (/ for the homepage).

Why use React router? It allows you to build single page web applications (SPA) with navigation. React Router uses component structure to call components, which display the appropriate information. React router also allows the user to utilize browser functionality like the back button, and the refresh page, all while maintaining the correct view of the application.

For this tutorial, you should feel comfortable with web development concepts such as DOM (Document Object Model), HTML, npm, and JavaScript.

Now, here's what will be covered:

If you're new to React or need a refresher on the fundamentals, you can check out my article What is React? A tutorial on how to get started.

What is React Router?

React router is a library that allows you to handle routes in a web app, using dynamic routing. Dynamic routing takes place as the app is rendering on your machine, unlike the old routing architecture where the routing is handled in a configuration outside of a running app. React router implements a component-based approach to routing. It provides different routing components according to the needs of the application and platform. The following illustration shows how react router’s dynamic routing works as compared to traditional static routing:

Alt Text

Here is a really simple single-page app (SPA) that implements routing using React Router. This code belongs to the routes.js files of a React app. To see the full app in action, visit my original post.

import React from 'react';
import { Home } from './views/Home';
import { About } from './views/About';
import { NavBar } from './components/NavBar';
import { Route, Switch, Redirect } from 'react-router-dom';

export const Routes = () => {
  return (
    <div>
      <NavBar />
      <Switch>
        <Route exact path="/Home" component={Home} />
        <Route exact path="/">
          <Redirect to="/Home" />
        </Route>
        <Route exact path="/About" component={About} />
      </Switch>
    </div>
  );
};

There is one component NavBar that appears on the top of the app and enables switching between different views namely, Home and About. The router.js file is where all the routes of the SPA can be defined.

In routes.js, first, the components, views, and required packages are imported (Line 1-5). Then all those routes are defined that the SPA can take, keeping the Home component the default route (Line 13-15). And then all the possible routes are simply added using the following template, between <Switch> tags:

<Route exact path="/specifiedPath" component={componentName} />

The component (componentName) will be rendered when the "/specifiedPath" is visited on the web app.

Importing these routes from routes.js to index.js file, putting them inside a <Router> tag is all that is needed as the last step.

React Router can be installed using the npm cli utility:

> npm install react-router-dom

… and then can be imported and used inside the SPAs.

Client vs. Server Side

We can't have a conversation about routing and React Router without mentioning client side and server side. Client side is the browser. Its processing happens on the local machine – like rendering a user interface in React. Server side is where the information is processed and then sent through to a browser.

Alt Text

Server-side means that the action takes place on a web server. Most JavaScript can be done without access to a web server. Client-side means that the JavaScript code is run on the client machine or the browser when we’re talking about web applications. Server-side JavaScript means that the code is run on the server which is serving web pages.

React Router vs. React Router DOM

React Router DOM is DOM bindings for the React Router, or in simpler terms React Router for websites. In contrast, React-Router-Native is bindings for an app development environment using React Native – most often mobile phone Operating Systems – like iPhone/iOS.
To return to our web vs. native development topics, React Router come in 2 flavors, just like React:

  • Web
  • Native

Single Page Applications

Single page applications dynamically rewrite the web page with new data from the server, instead of the default method of the browser loading entirely new pages. When – you – the user, clicks a link, you don’t go to an entirely new page. Instead, the new context loads inline on the same page you’re already on – so only the necessary components of the page render.

Alt Text

Click on Ms. Maisel:

Alt Text

Single page applications can make the website seem more like a native app. A lot of web pages are written as single page applications where each component renders independently.

Single page applications are where React Routing comes into play. When people use a website, there are some things they expect to work – like the back button on the browser, or the URL signifies the view they are currently looking at. This can get complicated for the developer to build in Single Page applications – there’s a “deep link” problem. Some piece of information on a Single Page app may be buried deep underneath many components, so how does the developer make sure the correct URL showing that component displays in the address bar? Through routing – which is why we’re learning about React Router. React Router is a JavaScript library that provides routing capabilities to single page applications built in React.

Conceptual steps to building a single page app:

  • Main parent component
  • Initial Frame: static (aka app frame)
    • Could be one invisible HTML element that acts as a container for all the web pages content, or could be a header, or title.
    • In the Dogs SPA graphic above – the two components on the left showing “Contact” and “Care 101” stay the same in both views of the SPA. The center section renders with a picture of Ms. Maisel when that link is clicked.
  • React Router defines a Routing Region
    • Navigation links
    • Container to load content into – in our picto graphic above – the center region where the picture of Ms. Maisel shows up.
  • Component provides the foundation for the navigation, browser history handling, so users can use the backward & forward buttons.

React Router Tutorial: Adding Navigation to your React app

Let’s do a quick example to see the very basics of React Router – one step farther than a Hello World, but not by much. We’ll do React Router web for our example. First, we’ll follow some operational steps to get the React Router example going, then dive into the JavaScript code in depth.

JavaScript

const {
  BrowserRouter,
  Route,
  Link
} = ReactRouterDOM

// Set up pages using the React Router Link element for navigation - instead of <a></a>
const App = () => (
  <div>
    <h1>React Router Example</h1>
    <ul role="nav">
      <li><Link to="/client">Client Side</Link></li>
      <li><Link to="/server">Server Side</Link></li>
    </ul>

    <div>
      <Route path='/client' component={Client} />
      <Route path='/server' component={Server} />
    </div>
  </div>
)

// Populate sample pages. 
const Client= () => <h3>What is client side?<body><li>Browser</li><li>Runs on local machine</li><li>React renders user interface</li><li>React Router adds clickable links</li></body></h3>

const Server= () => <h3>What is server side?<li>node.js - JavaScript everywhere!</li></h3>

//Render app into the root HTML DOM node
ReactDOM.render((
  <BrowserRouter>
    <App/>
  </BrowserRouter>
), document.getElementById('root'));

HTML

<div id='root'></div>

When you run the code, you should see this output:

Alt Text

These links will now be clickable thanks to React Router! Now you could spruce this up and add CSS, but for this example, we'll keep it simple.

Now, let's dive into what is actually happening with this code:

Breaking down the JavaScript

Part 1: Render() Function

//Render app into the root HTML DOM node
ReactDOM.render((
  <BrowserRouter>
    <App/>
  </BrowserRouter>
), document.getElementById('root'));
  • Remember from the earlier React article about the render() function?

    • Render() is taking the logic from the React element in the JavaScript side, and displaying it in the User Interface.
    • React elements are plain objects that are cheap to create, unlike DOM objects. Speed is a benefit of React. React DOM updates the root DOM node in the HTML window to display the rendering of the React element in the user interface.
  • <BrowserRouter> tags

    • Set up your app to work with React Router by wrapping the app in <BrowserRouter> element. Everything that gets rendered goes inside the <BrowserRouter> element. tag
  • The app tag refers to the const App = () => App function in the JavaScript code.

Part 2: Sample Pages Section

// Populate sample pages. 
const Client= () => <h3>What is client side?<body><li>Browser</li><li>Runs on local machine</li><li>React renders user interface</li><li>React Router adds clickable links</li></body></h3>

const Server= () => <h3>What is server side?<li>node.js - JavaScript everywhere!</li></h3>
  • In this example, sample pages are made through HTML tags. In a real app, sample pages might be populated by an API, or be in their own separate JavaScript files in the same project, because pages can get complicated.

Part 3: App Function

  • Let’s start with <Route> tags. <Route> tags represent links between components. Route tags are React Router syntax similar to <a> tags in normal HTML.
<div>
    <Route path='/client' component={Client} />
    <Route path='/server' component={Server} />
</div>
  • Here, we added 2 routes. Let's examine the first Route example client:
    • component={Client}” tells JavaScript to link to the const Client sample page
    • Route path='/client' tells JavaScript to add “/client” to the URL when clicking that link
  • App function: Link element – add clickable links!
<ul role="nav">
      <li><Link to="/client">Client Side</Link></li>
      <li><Link to="/server">Server Side</Link></li>
</ul>

Benefits of React Router:

  • Add routing to different views/components on Single Page Applications
  • Composable
  • Easily add links after designing the webpage
  • React Router conditionally renders certain components depending on the route from the URL.

Wrapping up

Now that you've explored React Router and it's capabilities, it's time to start building your own React applications.

The Road to React: the one with hooks is a great project course. Throughout, you'll be learning all the ins and outs of React and by the end you will have built a fully-functional Hacker News App that will be a great addition to your portfolio.

Resources

Articles

Other helpful resources

Posted on by:

amandaeducative profile

Amanda Fawcett

@amandaeducative

Content Marketing Manager for Educative, Inc. (she/her) Learning web dev from scratch!

Educative

Level up on in-demand tech skills - at your own speed. Text-based courses with embedded coding environments help you learn without the fluff.

Discussion

pic
Editor guide
 

Thanks for nice post.