This Is How I Created a Simple App Using React Routing

React Routing Interactive Tutorial

React Routing Interactive Tutorial

This tutorial explains how I created a simple app using React Routing.

Table of Contents

  • Motivation
  • Getting Started
  • Introduction to react-router-dom
  • Let’s create the app
  • Additional Work

Motivation

As a full-stack developer, I was used to jQuery for front-end development. However, lately, I’m much into React because it makes creating interactive UIs painless. After learning React core concepts, I created my first production React application. While creating this, I tried to create my own routing library using onpopstate, window.history, etc (PLEASE DON’T DO THAT). Finally, I understood that it’s one of the biggest mistakes I did in 2019.

For the first single-page app I created in 2020, I decided to use the React Router. Wow! Creating the app was 1000 times easier than earlier, and no headaches 🤗 (That’s why 800k+ repositories use this router).

The first thing I did was to learn how to use the React Router. For this, I used a learning-by-doing method. In this article, I’ll explain how I created a simple app using React Routing.

Getting Started

In this guide, we will be using the latest version (5.1.2) of the react-router-dom library, which includes DOM bindings for the react-router library. So, we can use it in our web app.

To get started, first, let’s create a React app. The first option is by using create-react-app to get started (Not used in this tutorial). If you aren’t familiar with it, you can learn more from the create-react-app getting started guide.

If you like that option, here’s the way.

Then, install the react-router-dom package (~415KiB).

Finally, start the dev server, which will watch for file updates and automatically reload the app in real-time.

However, I don’t like to download 100MB+ packages to my computer for a small learning project like this. Many developers faced the same problem. codesandbox.io is the solution.

Visit the platform and use the template React (react-create-app).

Create Sandbox: create-react-app

Create Sandbox: create-react-app

Then, add the dependency react-router-dom (Choose the latest version).

Adding the dependency: react-router-dom

Adding the dependency: react-router-dom

It’s the same process as doing in the local machine. Instead of the local environment, here you have a virtual one. You can save it and share it with friends too.

Introduction to react-router-dom

In my opinion, react-router-dom is a great invention (and the only option available) to handle the browser routes in React. If you know how to think in react, you know how to use the library already.

Before we start coding the app, let’s familiarize ourselves with the library react-router-dom.

This library includes three main component types.

  1. Wrapper (Router) – <BrowserRouter> and <HashRouter>
  2. Navigators – <Link>, <NavLink>, and <Redirect>
  3. Route Matchers – <Route> and <Switch>

1. Wrapper (Router)

Called “Router” in the official documentation and the package, these are actually wrappers. You have to wrap Navigators and Route Matchers in a Router.

  • <BrowserRouter> uses regular paths.
  • <HashRouter> use (ugly, at least for me) hash of the URL.

Most of the new apps use regular paths to keep the URLs professional and clean. So, we will use <BrowserRouter> in this tutorial.

2. Navigators

As the name explains, these are used to navigate through the app.

  • <Link> – This is a <a> element. However, when clicked, rather than reloading the page, this will change the path. to attribute is used to specify the path.
  • <NavLink> – Same as <Link>, but includes the special attribute activeClassName attribute which we can use to add a class when the to is matched. We will be using in this tutorial

Ex:

Cool right? However, I (maybe you too) have the question of why developers of react-router-dom didn’t add that attribute to <Link>. If you know, share it in comments.

  • <Redirect> – Used to redirect to a page.

Ex: If you need to redirect from / to /app:

3. Route Matchers

These are like conditionals in Javascript. If the path is matched, the inner JSX will be rendered. (You may have inferred it already from the last example).

  • <Route> – like an if statement.

By default, path="/" will match all /, /app, etc. exact is used to prevent it. You can also use the component attribute. (<NavLink> also support exact)

  • <Switch> – like a switch statement with break statements in all the cases. It can wrap <Route> and will only render the first matched element.

Another use of Switch is to render 404 pages. When no path is defined in Route, Switch will render it. So, in the end, we can add a 404 page.

So, here’s the stack we will be using in this tutorial.

  1. <BrowserRouter>
  2. <NavLink>
  3. Both <Route> and <Switch>

Let’s create the app

We will be creating a blog using the single-page app model. Usually, blogs like WordPress reload pages when navigating. We can use react to create a single-page blog.

Here’s our plan:

A plan

A plan

If you get stuck anywhere during this tutorial, you can refer to the codesandbox URL given at the bottom of this tutorial. A demo is also available.

Let’s start creating App.js.

Here we wrap the whole app in a <BrowserRouter> (Imported via import { BrowserRouter } from "react-router-dom";).

The view is divided into two components: <Header> and <Body>.

Header.js

In the header, we include the links using <NavLink>. To prevent repetition of className and activeClassName, I’ve created a new function HeaderNavItem.

Body.js

Body is where we will render the components based on the URL path. In the body, we use <Route> and <Switch> from react-router-dom.

<About> and <Contact> are simple components like the following. You can customize them if needed.

About.js

Contact.js

<Blog> (Blog.js) is where we list the posts. However, we need some posts first to load. You can fetch it from an API (Check my previous post) or load it from files. To learn react router, how you load posts is not significant. Here, I have used a JSON file to store the posts to make it simple.

_posts.json

You can add whatever posts you need. (Those are just some funny posts)

Blog.js

As we don’t need an active class added when the post is shown, I have used <Link> instead of <NavLink>. When the user clicks on post-listing, the location will be changed to /post/whatever-slug-in-json-file.

We list the posts by looping through the postsData. (See React Lists and Keys) for more details.

If we look at our Body.js, you will notice this.

Here we use :slug as an URL parameter. So, <Post> component will be able to access the part after /post/ easily using props or hooks.

Finally, Post.js (where Posts are shown)

import { useParams } from "react-router" is used to import the useParams hook. useParams returns an object containing all URL parameters with their key and value. Use object destructuring to get the needed value (slug in this case).

findPostBySlug() is a simple function to find the article by slug. (Thanks to Šime Vidas on Stackoverflow)

However, if you aren’t comfortable with React hooks, you can access the URL parameters via props.match.params.

Additional Work

1. Adding CSS

First, make sure your app is beautiful. Add some CSS! Here’s what I used.

2. Programmatical Navigation

You can use <Redirect> when rendering as shown above. If you need it to do in any other function in a child component of <Route>, use props.history.push function.

Summary

Here’s how we routed our app.

  • / – Posts Listing
  • /post/:slug – A post
  • /about – About page
  • /contact – Contact page

Test it out.

Conclusion

Here’s what I found on a rating website.

React Router pic

React Router pic

The React Router doesn’t have an alternative because it does everything. There’s a lot of other options/features you can use in the Router. The official documentation by react training outlines those with examples.

Have questions? Let me know below.

Thank you for reading.

About the author

Stay Informed

It's important to keep up
with industry - subscribe!

Stay Informed

Looks good!
Please enter the correct name.
Please enter the correct email.
Looks good!

Related articles

Create simple POS with React.js, Node.js, and MongoDB #17: Stat screen

Now, we are going to implement the final chapter for this tutorial series where we are implementing a graphical representation section on our ...

16.10.2020

How to write effective tests for React apps with react testing library?

Testing might seem like extra work at first. Why write tests when you could be delivering features for your application? Writing tests may seem like ...

Create simple POS with React.js, Node.js, and MongoDB #16: Order Screen

In this chapter, we are going to create an order page. The order page displays the products and the calculator to help calculate the total price. ...

2 comments

Nikita Bragin February 21, 2020 at 11:54 am
0

thanks for sharing! although hookrouter might be a great alternative

 
Supun Kavinda February 22, 2020 at 10:15 pm
0

I just noticed that library (hookrouter). However, since react-router 5.1, hooks are supported.

https://reacttraining.com/react-router/web/api/Hooks

Sign in

Forgot password?

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy

Password recovery

You can also try to

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy