Home/Blog/Tutorials & Guides/React Router Tutorial: Adding Navigation to your React App
Home/Blog/Tutorials & Guides/React Router Tutorial: Adding Navigation to your React App

React Router Tutorial: Adding Navigation to your React App

7 min read
Apr 22, 2020

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

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.

Here’s what will be covered:



Learn how to create web apps with Global State

By the end of this course, you will be ready to build more advanced applications without having to do unnecessary re-rendering. You’ll also have a nice piece to showcase in your portfolio

React Tracked for Beginners



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.

Here is a really simple single page app (SPA) that implements routing using React Router.

export { default as NavBar } from './NavBar';

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.

Server side is where the information is processed and then sent through to a browser.

widget

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.


Keep the learning going.#

Learn React without scrubbing through videos or documentation. Educative’s text-based courses are easy to skim and feature live coding environments - making learning quick and efficient.

React Tracked for Beginners



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.

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 a 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.

widget

Click on Ms. Maisel:

widget

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. 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.

Enjoying the article? Scroll down to sign up for our free, bi-monthly newsletter.


React Router Tutorial: Adding Navigation to your React app#

Let’s do a quick example to see the very basics of React Router. 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.

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'));

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

widget

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 an 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 course React Tracked: Creating Web Apps with Global State is a great project-based place to start. 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.

Happy learning!


Written By:
Erin Doherty
 
Join 2.5 million developers at
Explore the catalog

Free Resources