OpenReplay
Navigate back to the homepage
BLOG
Browse Repo
Back

Understanding React Router with a Simple Blog Application

Queen Nnakwue
October 8th, 2021 · 6 min read

Introduction

React router is arguably one of the coolest feature there is in React. It is a famous library and familiarity in knowing how to use this library is expected for everyone who’s learning React. The reason is very simple. When using a website, it is essential for users to be able to view different pages seamlessly, or to navigate from one page to another. React Router is the library that makes this possible.

React creates single-page application and react router plays an important role to display multiple views without having to reload the browser in a single page application.

It is worth noting that it is almost impossible to display multiple views in React single-page applications without React Router. Websites that use react router for rendering multiple views for their app include, but not limited to Facebook, Instagram, Twitter, to mention a few.

This tutorial will be divided into two different sections. In the first section (part 1), we are going to learn some of the fundamentals of React Routing, as listed below:

  • What is Routing?
  • What is React Router DOM
  • BrowserRouter, Route, Switch and Link simply explained
  • And lastly, we will look at React router with hooks, focusing on useHistory, useParam, and useLocation.

In the second section (part 2), we are going to use all the knowledge we garnered in the first section to build a simple multi-page blog.

PART 1

What is Routing

Routing enables navigation from one view to another in a web application based on action or request. It is the ability to move from one page to another when a user click some element like link, button, icon, image, and so on within the application.

In other words, it is a process in which a user is directed to different pages based on their action or request.

React Router on the other hand, is used to create various routes in a single-page application. It is the standard routing package used in react to change views and move between pages.

For instance, when a user types a specific URL into the browser, the user is redirected to that particular route if the URL path matches any route inside the router file with the help of react router without the browser reloading.

To make use of React Router, we will need to use a package called React-Router-DOM. We will look at that in the next section.

What is React Router DOM

Now that we have a basic understanding of React Router, let’s take a cursory look at the React-Router-DOM. The React Router DOM is the node module that is specific to routing in web applications as opposed to mobile.

It allows engineers to create routes for a React single page application.

Simple enough. Next, let’s cover the components of react-router.

The BrowserRouter, Route, Switch and Link are all components of the React-Router. These components are divided into three categories.

The first category is routers, for example <BrowserRouter>. The second category is route matchers, such as <Route> and <Switch> and the last category is navigation, such as <Link>, and <Redirect>

Let’s take a look at each of these components individually.

  • <BrowserRouter>: BrowerRouter is a router implementation that has the ability to incorporate routing in react. It uses the HTML5 History API which include pushState, replaceState and the popState event to keep our UI in sync with the URL. It is the parent component that is used to store all other components and it uses regular URL paths.
  • <Route>: Route is the conditional component that renders a component based on the URL defined or the URL it is pointing to. In other words, it is a component that renders some UI when its path matches the current URL.
  • <Link>: Link component is used to create links to different routes and implements navigation around the application. Links accepts the to prop, which signifies where we want the link to navigate our user to.
  • <Switch>: The switch component is used to render only the first route that matches the location rather than rendering all matching routes.

Note: We will use all these components to build a simple blog application in a bit. Keep reading!!

Above all these powerful components, there are some very useful hooks that are really helpful by supplying additional information that we can use within our components. They are: useHistory, useParam, and useLocation:

useHistory

According to the react router doc, the useHistory hook gives you access to the history instance that you may use to navigate. Through the history object, we can access and manipulate the current state of the browser history.

useParam

The useParam hook returns an object of key/value pairs of URL parameters where the key is the parameter’s name and the value is the parameter’s current value. In other words, it provides access to search parameters in the URL.

useLocation

The useLocation hook is equivalent to the useState but it returns a new location whenever the URL changes. In simple terms, the useLocation hook returns the location object that represents the current URL.

PART 2

Now it’s time to use the knowledge we’ve acquired in the first section to build a single page blog application so we can have a better understanding of routing in React. Our blog will have a navbar including the following functionalities:

  • Signup/Login page
  • Add new Post
  • Show all post
  • a toggle button to create a new post
  • 404 page

And finally, we are going to use react router to link all of our pages together such that a user is able to seamlessly navigate between pages in our application.

To follow along, kindly clone the repo here and start the application on your local machine using npm start

You should see the screenshot below on your browser.

null

Now, its time for us to implement routing on our app to make it dynamic.

Let’s begin!

Step 1:

We need to install react-router-dom via npm to handle the routing on our terminal by running

1npm install react-router-dom

Step 2:

Lets extract some code from our Home.jsx file and create a new file: Navbar.jsx.

Cut the following code snippets from your Home component and paste it inside your Navbar.jsx file

1<h2>Nicole's Blog.</h2>
2<div className='navbar__list'>
3 <ul>
4 <li>
5 Register
6 </li>
7 <li>
8 Login
9 </li>
10
11 <li>
12 Write a Story
13 </li>
14 </ul>
15</div>

Now, let’s update our Navbar.jsx file by adding the following lines of code

1import React from 'react';
2import '../styles/Navbar.css';
3import {Link} from 'react-router-dom'
4function Navbar() {
5 return (
6 <div className='navbar'>
7 <h2>Nicole's Blog.</h2>
8
9 <div className='navbar__list'>
10 <ul>
11 <li>
12 <Link to="/Login">Login</Link>
13 </li>
14 <li>
15 <Link to="/Register">Register</Link>
16 </li>
17 <li>
18 <Link to="/CreatePost">Write a Story</Link>
19 </li>
20 </ul>
21 </div>
22 </div>
23 )
24}
25export default Navbar

Here, we imported Link from react-router-dom. Link is just like an anchor tag <a> with a real href attribute in HTML. It has similar functionality and does the same thing like an anchor tag does.

So instead of using <a href> here, we used Link to. For example, on click of the Login button on the navbar, a user is redirected to the Login page without the page refreshing or reloading. This applies to all the other links in the navbar.

Step 3:

Now it’s time to import all of our components into our App.js file and see how we can use the categories we learnt in the first part of this article to make our blog app fully dynamic like so:

1import {BrowserRouter, Route, Switch} from 'react-router-dom';
2import Home from './Components/Home';
3import Login from './Components/Login';
4import Register from './Components/Register';
5import CreatePost from './Components/CreatePost';
6import AllPost from './Components/AllPost';
7import Navbar from './Components/Navbar';
8function App() {
9 return (
10 <BrowserRouter>
11 <div className="App">
12 <Navbar />
13 <Switch>
14 <Route exact path='/' component={Home}>
15 <Home />
16 </Route>
17 <Route exact path='/Register' component={Register}>
18 <Register />
19 </Route>
20 <Route exact path='/Login' component={Login}>
21 <Login />
22 </Route>
23 <Route exact path='/CreatePost' component={CreatePost}>
24 <CreatePost />
25 </Route>
26 <Route exact path='/AllPost' component={AllPost}>
27 <AllPost />
28 </Route>
29 </Switch>
30 </div>
31 </BrowserRouter>
32 );
33}
34export default App;

This is how we incorporated react-router into our application. First, we imported {``BrowserRouter, Route, Switch} from ‘react-router-dom’. Remember in the first part of this article we said <BrowserRouter> has the ability to incorporate routing in react. That explains why we are wrapping all of our components that we want the routing to be in with it.

On line 12, just before the Switch component, we rendered the Navbar component. This is because we want our navbar to be available to all our pages in our application.

We also used the Switch component to render the first route that matches the location rather than rendering all matching routes. If we exclude the Switch component from our code, all the routes will be rendered on a single page.

As we already know, the Route renders a component base on the URL. In the above code, we gave the Routes different path depending on what we want it to render on our browser. We also specified the component by adding a prop, component and setting it to the component we want to render.

Still on the Route component, we used the exact keyword to specify the exact path for specificity. Otherwise, whenever the Switch component sees this / in our URL, it will only render the first route just beneath it even though we specify the path we want rendered.

To better understand this, try removing the exact keyword from the Route component. Just play around with the code to gain more clarity.

On line 14-15, we didn’t specify the path to our route but we passed a prop Home because we want to be able to render the Home page when a user visits our page for the first time.

Open Source Session Replay

Debugging a web application in production may be challenging and time-consuming. OpenReplay is an Open-source alternative to FullStory, LogRocket and Hotjar. It allows you to monitor and replay everything your users do and shows how your app behaves for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder. OpenReplay is the only open-source alternative currently available.

OpenReplay

Happy debugging, for modern frontend teams - Start monitoring your web app for free.

REDIRECT

Next, let’s demonstrate a feature that will allow only logged-in or registered users to write a story on our blog.

We are going to do that inside our App.js file using the Redirect component like so:

1import {BrowserRouter, Route, Switch, Redirect} from 'react-router-dom';
2
3<Redirect from='/CreatePost' to='/Register' />

This is very self-explanatory. Here, we imported the Redirect component from the react-router-dom like the other component and on line 3, we are using it to redirect our user(a non-registered user in this scenario) to the Register page when they try to write a story without registering/signing in first.

404 Page

Finally, let’s add a 404 page to our application such that if a user clicks or types a URL that isn’t on our app, such a user will be redirected to the page. Again, create a NotFound.jsx file in your components folder and add the following code snippets

1import React from 'react'
2function NotFound() {
3 return (
4 <div>
5 <h1>404- Page not Found</h1>
6 </div>
7 )
8}
9export default NotFound

Next, import this file in your App.js file and add the following:

1<Route component=
2 {NotFound}>
3 </Route>

Let’s test this. When i try searching for a URL/page that doesn’t exist on our blog app, i got redirected to the 404 page like so:

null

Conclusion

In a nutshell, we looked at Routing in React from a beginner perspective by building a simple blog application. We also looked at react-router-dom and the different components with examples.

Hopefully, this article put you up to speed when building your next app.

You can find the code here- https://github.com/QNNAKWUE/react-blog

Thanks for reading!

More articles from OpenReplay Blog

How Relevant is Still TypeScript in 2021?

Is TypeScript still the best type-safe language for the web in 2021?

October 7th, 2021 · 5 min read

The Ultimate Guide to Getting Started with the Rollup.js JavaScript Bundler

Learn how to use this JavaScript bundler with easy-to-follow examples

October 7th, 2021 · 6 min read
© 2021 OpenReplay Blog
Link to $https://twitter.com/OpenReplayHQLink to $https://github.com/openreplay/openreplayLink to $https://www.linkedin.com/company/18257552