Easy Guide to Understanding React Router for beginners

Easy Guide to Understanding React Router for beginners

React-router is a third-party library that’s popularly accepted for its design and simplicity. It provides us an easy way to navigate through a React application with several views (pages / URLs).

In this article you are going to learn what react-router is, why use react-router in your react application, how to apply react-router, starting from the basic installation steps, various react-router components, and how to get your application fully going with react-router.

Before I continue, I will like to share a short experience with you.

In my early days of learning react, I was working on a side project to solidify my knowledge on react only to stumble on a problem which is, “how can I route between pages in my application?” This problem got me searching the internet, watching several YouTube videos, and dissecting the React-router documentation for days before I could get an understanding of what react-router is and the principle behind certain components needed for my application. This prompted me into writing this article to save other persons from going through such a hectic process as I did.

This article is meant for beginners trying to understand what react-router is and how to apply it in your application. Notwithstanding intermediate or experts can also use this as a refresher to their previous knowledge about react-router.

Why React router?

Just as we navigate (Route) from one page to the other using the HTML anchor tag

<a href=’/’>Link</a>

likewise, react-router lets you handle routing in a declarative manner. The declarative routing approach allows you to control the data flow in your application.

What is Routing?

Routing refers to the process of moving between different views of an application such as when a user clicks an element (link, button, image, etc.) or enters a URL within the application.

Routing is also the process of keeping the browser URL in sync with what’s being rendered on the page. i.e if a user should navigate to href=’/about’ then the about page component should be rendered accordingly.

Let’s quickly look at how we can set up a React-router in our React application.

Installation

Before you can start using react-router, you have to install the react-router-dom package.

Kindly enter the following installation command in your terminal.

You can use either npm or yarn depending on your preference. For the purpose of the study, we will be going with npm

npm install react-router-dom

Three (3) basic components in React-Router

React router API’s such as

<BrowserRouter>

This is the most used because it uses regular URL paths. e.g. oci.com.ng/about

<HashRouter>

which stores the current location in the hash portion of the URL. e.g. oci.com.ng/#/about.

Note: The hash is never sent to the server.

Route matcher's: like

<Route> and <Switch>

React-router navigation like

<Link>, <NavLink> and <Redirect>

which will be discussed extensively as we progress.

To use a router, just make sure it is rendered at the root of your element hierarchy. This means you have to wrap your top-level component

<App />

in a router.

indexjs.png

What is Route in React?

Let assume we have 3 components namely About, Contact, and Dashboard. The Route is a react-router package component responsible for rendering the exact UI (exact component) when the current location (URL) matches the route path.

about_route.png

Once a user clicks or navigates to a location (URL) that correspond to path=”/about”, the About component gets rendered on the UI.

Note: exact: is one of the properties of Route. When a value of true, it will match the location.pathname exactly.

What will happen without the exact props?

Assuming we have 2 Routes namely About and Home.

Home && about_route.png

Both will be rendered because of the “/” present in each Routes’s. But when exact is added and set to true it will match the exact path with the corresponding component. (Therefore, path=”/” becomes different from path=”/about”)

Switch

A switch component works just like our normal Switch statement. A Switch checks through all routes wrapped inside and renders the exact Route path that matches the current URL then stops (i.e after matching a particular path and rendering the UI, it doesn't check the rest of Routes).

switch.png

The link component works exactly like the anchor element (a href="/about") in HTML. The advantage of using the Link component is that it eliminates browser refresh compare to anchor tag in HTML. It is used to navigate between pages, automatically rendering a new view (UI) each time.

<Link to=”/about” >About </Link>

to refers to the location reference just like the href.

Note: when you go to your dev tool, you will discover that the Link is interpreted as an anchor tag.

The NavLink renders the same function as Link except for the extra features added. The NavLink comes with properties such as

  • activeClassName

  • activeStyle

  • isActive

  • strict

activeClassName

This refers to the class given to the element when it is active. The default class given is active

Let’s create a class called active in our stylesheet and import it to our App components.

active.png

Immediately after your Link is active, the color changes to red.

activeStyle(object)

It refers to the style we want to apply to the element when it is active.

Const active= {{fontSize: ‘2rem’, color: ‘red’, textDecoration: ‘underline’}}

We can then apply the active object(active) which is a CSS style to our component.

isActive (function)

Is a function used to add extra logic for determining if a link is active or not.

activeStyle.png

Redirect

Have you ever tried redirecting a user to a different location when a particular condition is fulfilled or after a form is been submitted and validated? The Redirect component acts just like the server-side redirect does.

redirect.png

to: refers to the path (URL) to redirect to.

Creating a simple Navigation menu using React router

In this part of this article, we are going to create a simple navbar using react-router.

<nav>
    <ul>
        <li><Link to=”/”>Home</Link> </li>
        <li><Link to=”/about”>About us</Link> </li>
        <li><Link to=”/contact”>Contact us</Link> </li>
    </ul>
</nav>

Using the Switch component to check through each Route to be matched.

switch.png

Immediately any of the Routes matches the URL (I.e if the about us link is clicked the location.pathname (/about) is matched with the About Route and then rendered).

Just play around with the above example to get a deeper understanding of routing.

Conclusion

In this first part, we were able to establish the concept of react-router, its importance, and how to setup react-router in your application with the basic component needed to get you started. In our next series, we are going to look at how we can use all this to create a budgetary application

I hope you found this article useful? If you did kindly follow me to get updates on my upcoming article on protected routes and other topics lined up for you.

Thanks for staying around and hope to see you on my next article.