React Router DOM: How To Create A React Navigation Bar

Sept. 27, 2021, 11:08 a.m.
React · 9 min read
React Router DOM: How To Create A React Navigation Bar

Introduction

Every application is made up of different parts. These parts are generally connected directly or indirectly. In an application, a certain part can be accessed or visited by entering the URL specified for it. These URLs can be invoked on clicking elements such as buttons, text, images, and more. Such ability to move from one part of an application to another through URLs is known as routing. 

Routing is an essential part of a web application. Today, no web application is complete without proper routing. Routing is a basic concept in React development and every React developer should be familiar with it. In this tutorial, we will discuss everything related to routing in React with the help of examples.

 

React Router

React Router is the core library used to create routing in react-based applications. It comes in three different variants - react-router, react-router-dom, and react-router-native. While react-router is the core variant, and react-router-native is used for mobile applications, react-router-dom is specifically created for web applications. 

To use routing, we need to install react-router-dom from the NPM using the following code. 

npm install react-router-dom

There is no need to install the core library because the react-router-dom will install the functionalities provided by it. 

 

Understanding how routing works

Now we know what is routing and which library is required for it in a React application. Let’s understand the concepts related to routing while building a simple React application.

Following is the App.js file with the Header component. 

import "./App.css";
import Header from "./Components/Header";

function App() {
  return (
    <div className="App">
      <Header />
      <hr />
    </div>
  );
}

export default App;

As of now, this is how it looks.

React Router DOM App.js

 

Router

The “react-router” library provides different types of routers such as BrowserRouter, MemoryRouter, and HashRouter. For a web application, BrowserRouter is a suitable router.

The application will be wrapped in BrowserRouter so that it can handle different URLs. To use the BrowserRouter, import it from the react-router-dom and wrap it around the application.

import { BrowserRouter as Router } from "react-router-dom";
import "./App.css";
import Header from "./Components/Header";


function App() {
  return (
    <Router>
      <div className="App">
        <Header />
        <hr />
      </div>
    </Router>
  );
}



export default App;

First, the BrowserRouter is imported as “Router” and then the Router is wrapped around the entire application.

Note: It is not necessary to import the BrowserRouter as “Router”. It can be imported as it is. 

With a Router placed in the App component, routing can be defined anywhere inside it. But it is recommended to define all the routes in one place only. So the App component will be the focus of this tutorial.

 

Routes

Our application only displays a header right now. We will create different routes, each rendering a different component below the header. 

A route is basically a path or URL that when accessed renders a specific component. For example, 

  • “/home” will render the home component
  • “/about” will render the about component
  • “/contacts” will render the contacts component

To create a route, the <Route /> has to be imported from react-router-dom. The URL is defined in the <Route /> component using the “path” prop. 

Observe the following code.

<Route path = {"/home"} />

The route has a path but how will it know which component to render with “/home” is accessed? The <Route /> component provides three different props to handle what is going to happen when the route is accessed. These props are:

  • component
  • render
  • children

 

Let’s create a new component and name it “Home”.

const Home = () => {

  return <h2 style={{ textAlign: "center" }}> Home page </h2>;

};

export default Home;

The Home component will be rendered when the “/home” route is accessed. To do this, we need to create a route using the component prop.

 

<Route path="/home" component={Home} />

 

Let’s add this code to the App.js file.

import { BrowserRouter as Router, Route } from "react-router-dom";
import "./App.css";
import Header from "./Components/Header";
import Home from "./Components/Home";


function App() {
  return (
    <Router>
      <div className="App">
        <Header />
        <hr />
      </div>
      <Route path="/home" component={Home} />
    </Router>
  );
}


export default App;

Now, let’s see what happens when “/home” is accessed. 

React Router Homepage

 

The Home component is rendered on the screen.

Apart from component props, we can also use render. The render props let us write inline functions. For example,

<Route path="/home"
   render={() => <h2 style={{ textAlign: "center" }}> Home page </h2>}                                                                              
/>

The above route renders the same thing as the earlier code. Only difference is that here an inline function is used.

The third prop is children. It is similar to the render prop but it renders the component even if there is a match or not. 

 

Exact and Switch

Observe the following routes.

<Route path="/" component={() => <h2 style={{ textAlign: "center" }}>Dummy route</h2>} />

<Route path="/home" component={Home} />

What do you think will happen if “/home” is accessed? The Home component should render, right? 

React Router Dummy page

 

Both the routes are invoked. Why? This is because the link “/home” contains both “/home” as well as “/”. To counter such situations where the routes may share the same path, we have the “exact” prop.

<Route exact path="/" component={() => <h2 style={{ textAlign: "center" }}>Second route</h2>} />

<Route exact path="/home" component={Home} />

Now, let’s see what happens when “/home” is accessed.

React Router homepage

 

Observe the following routes.

<Route path="/home" component={Home} />

<Route path="/home/categories" component={Categories} />

Both of these routes have “/home” in common. If “/home/categories'' is accessed, both the components will be rendered. The react-router-dom provides Switch to wrap the routes. The Switch returns only the first matched route. 

<Switch>
      <Route path="/home" component={Home}/>
      <Route path="/home/categories" component={Categories} />
</Switch>

Now, if we try to access “/home/categories”, instead of rendering both, it will render the “Home” component because “/home” is encountered first. This is not what we want right? So the exact prop is used with the Switch to avoid undesirable results. 

<Switch>
      <Route path="/home" component={Home} exact />
      <Route path="/home/categories" component={Categories} />
</Switch>

React Router exact switch example

 

 

Navigation

Till now, we discussed how the routes are created. To access every route, we had to type the path in the address bar of the browser. But we don’t do this in real life, right? Usually, we click on an element on the page to move from one part to another. This is called navigation. 

The react-router-dom provides in-built support for creating efficient navigation. 

Link

The <Link> provided by react-router-dom is used to navigate from one place to another. Let’s add two buttons in the App.js file.

<Router>
      <div className="App">
        <Header />
        <hr />
        <button>Go to Home</button>
        <button>Go to Categories</button>
      </div>

      <Switch>
        <Route path="/home" component={Home} exact />
        <Route path="/home/categories" component={Categories} />
      </Switch>
</Router>

The <Link> works like the <a> tag provided by HTML. Let’s wrap the buttons with the <Link> and give them appropriate paths.

 

<Link to="/home">
     <button>Go to Home</button>
</Link>

<Link to="/home/categories">
     <button>Go to Categories</button>
</Link>

 

This is how the App component looks. 

React Router with Buttons

 

On pressing the “Go to Home” button, the Home component will render, and on pressing “Go to Categories”, the Categories component will render.

 

Redirect

Now, suppose, the “Categories” component should be visible only when the user is logged in. If not, whenever the user clicks the “Go to Categories” button, he should be redirected to the “Home” component. In such cases, we will use the <Redirect> component. 

Let’s make the change in the route for “Categories”.

<Route path="/home/categories">

   {login ? <Categories /> : <Redirect to="/home" />}

</Route>

In the App.js file, I declared a boolean variable named “login” for testing. If the value of “login” is true, then the “Categories” component will be rendered but if the value is false, then it will be redirected to the “/home” route. 

 

Dynamic routing

Now suppose we have multiple categories. For example, Apple, Samsung, OnePlus, LG, and Google. One way is to create a specific route for every category. 

<Route path="/home/categories/apple" />

<Route path="/home/categories/samsung" />

<Route path="/home/categories/oneplus" />

<Route path="/home/categories/lg" />

<Route path="/home/categories/google" />

 

What if we have one hundred categories? It is not an efficient way to create routes. So, here comes the concept of dynamic routing. 

First, let’s create a list of categories in the “Categories” component, each with an appropriate link. 

import { Link } from "react-router-dom";


const Categories = () => {
  const login = false;



  return (

    <div>
      <h2> Categories </h2>
      <ul>
        <Link to="/home/categories/apple">
          <li>Apple</li>{" "}
        </Link>
        <Link to="/home/categories/samsung">
          <li>Samsung</li>
        </Link>
        <Link to="/home/categories/oneplus">
          <li>OnePlus</li>
        </Link>
        <Link to="/home/categories/lg">
          <li>LG</li>
        </Link>
        <Link to="/home/categories/google">
          <li>Google</li>
        </Link>
      </ul>
    </div>
  );
};

export default Categories;

Every category has a separate link, meaning, we have to create a different component for each category. No, there is no need to do so. Moreover, creating a separate component will increase the work because there can be any number of categories. We will use dynamic routing here for better efficiency. 

We have to create a route with parameters. For every category, the last part is different while the remaining part is the same, right? So the category will be the parameter itself. 

Following is how a route with parameters looks. 

<Route path="/home/categories/:category" />

In the above route, :category is the parameter. In simple words, the value of :category will be defined dynamically. 

For example, the route can be “/home/categories/apple”, or “/home/categories/google”, and so on. 

Similarly, we will have a single component that will load the details of a category according to the incoming parameter. The parameter is available in the props. It has a match object and in it, the params object contains the parameter. 

Observe the “Category” component. 

import data from "./data";



const Category = (props) => {

  const categoryDetails = data.find(
    (obj) => obj.category.toLowerCase() == props.match.params.category
  );



  return (
    <div className="App">
      <h2>Category: {categoryDetails.category}</h2>
      <h2>Range: {categoryDetails.priceRange}</h2>
      <h2>Ratings: {categoryDetails.rating}</h2>
    </div>
  );
};



export default Category;

In the “Category” component, the parameter is accessed using the props.match.params and then the relevant details are extracted from the “data” array. After that, details are displayed in the component.

So remember, the parameter is available in the params object, which in turn is present in the match object of the props received by the component. 

Now, we have a single route and a single component for different categories. 

For google,

React Router Google Path

 

For apple,

React Router for Apple Path

This is how dynamic routing is done.

 

Wrapping it up

Navigating from one place in an application to another is called routing. It is very important for a React developer to learn routing. In this tutorial, we discussed what routing is and how we can implement it in React applications. 

The react-router-dom is the primary library that is used for routing in React. We covered all the basic concepts such as router, creating routes, using the switch, link, and redirect. Another important concept for modern development is dynamic routing. Overall, in this tutorial, we discussed every basic concept with the help of an example to understand routing in React.

 






Post a Comment
Join the community

0 Comments
0
Written By
jatt01990