Routing in React JS with Example [Beginner’s Guide]

Read it in 17 Mins

Last updated on
21st Nov, 2022
Published
04th Nov, 2020
Views
1,156
Routing in React JS with Example [Beginner’s Guide]

Routing in reactJS is the mechanism by which we navigate through a website or web-application. Routing can be server-side routing or client-side routing. However, React Router is a part of client-side routing. 

Before proceeding further it is highly recommended you go over the official React.js certification course to familiarize yourself with the fundamentals of React.  

React Routing without any knowledge of it can be manually implemented using useState and JSX for conditioning. But being inefficient for large-scale applications like e-commerce, it still can act as a boilerplate for understanding routing and act as a base for React JS router for example. 

const[page, setpage] = useState("products") 
const routeTo = (newpage) =>{ 
  setpage(newpage) 
} 
<button onClick={()= routeTo("cart")}> Cart /> 
{page === "cart" && ( 
<Cart cart={cart} setcart={setcart}/>)} 

Server-side routing results in every request being a full page refresh loading unnecessary and repeated data every time causing a bad UX and delay in loading. 

With client-side routing, it could be rendering of a new component where routing is handled internally by JavaScript. The component is rendered only without the server being reloaded. 

React Router helps us to navigate the components and build a single-page application without page-refresh when the user navigates making it an effective UX experience. 

Web-Development is the heart of routing. Routing takes place efficiently in websites and so to understand it, one must know a basic boilerplate of web development complete course followed by React.js certification course to rocket-start React-Routing!  

Basic Routing 

React Router API

Browser Router or React Router API  is a most popular library  for routing in react to navigate among different components in a React Application keeping the UI in alignment with URL.  

According to react-router official docs, “ React Router is a fully-featured client and server-side routing library for React, a JavaScript library for building user interfaces.” 

Various Packages in React Router Library

There are 3 different packages for React Routing . 

  1. react-router: It is the heart of react-router and provides core functionalities for routing in web-applications and all the packages for react-router- dom and react-router-native  
  2. react-router-native: It is used for routing in mobile applications  
  3. react-router-dom: It is used to implement dynamic routing in web applications. 

How Routing Works / Routing Mechanism

We know routing is user-side navigation to different pages or different pages on a website. Every rendering mechanism has its own routing way to navigate but dealing with React Router here that comes under Client Side Routing but eventually under Client Side Rendering has a dynamic mechanism to look upon. 

Client Side rendering orders the server to deal with data only where the rest of all rendering and routing is handled by the client itself.  

Traditional routing has always requested the server to provide different index.html of different pages, but Client Side Rendering will only return one index.html file for Client Side Routing.  

This will give you the smooth Single Page Application Routing experience with forward and backward route ability using history API keeping the URL updated as well.

Installation and the Steps for React Router

Prerequisite for react router dom install: 

  1. You must have a react app created using create-react-app  
  2. The react app must be running with dummy code to procced for create react app router 

React Router will help us make a dynamic navbar with different links to route on, resembling a blog application where every link routes us to a  different new page. 

Step 1:  Run the following commands in terminal

npm install react-router-dom@6 
or 
yarn add react-router-dom@6 

Step 2: The package installs after the completion of npm and a message is received on the terminal varying with your system architecture.   

... 

+ react-router-dom@6 
added 11 packages from 6 contributors and audited 1981 packages in 24.897s 
  
114 packages are looking for funding 
  run `npm fund` for details 
  
found 0 vulnerabilities

And that’s it, we are ready to route! 

Now let's come to the source code after the fundamental installation:  

Source Code and Snippets

Step 1: After the installation of react-router-dom we can ensure that the package is successfully installed or not by checking the package.json file to see the installed react-router-dom module and its version.

{ 
   "name" : "reactApp", 
   "version" : "1.0.0" 
   "description" : "It is.a react app" 
  "dependencies" : { 
        "react" : "^17.0.2", 
       "react-dom" : "^17.0.2", 
       "react-icons" : "^4.3.1", 
       "react-router" : "^6.2.1", 
       "react-router-dom" : "^6.2.1" 
}, 

Step 2: Then you go straight to your index.js main page to activate BrowserRouter throughout the application running in the App.js file.

import {StrictMode } from "react"; 
import ReactDOM from "react-router-dom" 
import App from "./App" 
import {BrowserRouter} from "react-router-dom" 
const rootElement = document.getElementById("root") 
ReactDOM.render( 
<StrictMode> 
    <BrowserRouter> 
      <App /> 
   </BrowserRouter> 
</StrictMode>, 
  rootElement 
);

Step 3: Now we can make directories for the components or the pages we want to render. Either you can make separate folders or can have one folder with all components. Using a terminal or with a new tab, folders can be created with ease.

mkdir src/components/Home 
mkdir src/components/About 

Now we will create a component inside each directory we created above. Here we will first create a Home.js file for the Home directory.   

nano src/components/Home/Home.js  

Then add the basic component rendering code for it.  

function Home() { 
    return ( 
       <div> 
            <h1> This is the home page </h1> 
      </div> 
    ); 
} 
export default Home; 

Followed by  creating a About.js file for the About directory.   

nano src/components/About/About.js  

Then add the basic component rendering code for it.  

function About() { 
    return ( 
       <div> 
            <h1> This is the about page </h1> 
      </div> 
    ); 
} 
export default About; 

Step 4 :  Now comes the main App.js file which is the core of implementing all we have defined and declared till now by  defining  routes for each component  and where and which component they will render when the path matches with the base URL entered or clicked by the user. 

import {Routes , Route } from "react-router-dom" 
import Home from "./components/Home/Home" 
import About from "./components/About/About" 
function App(){ 
   return ( 
      <div className="App"> 
        <Routes> 
            <Route path="/" component={<Home/> } /> 
            <Route path="/about" component={<About/> } /> 
       </Routes> 
    </div> 
)} 
export default App 

This is how we install and set up the basic boilerplate using React Router. After that, it can be extended with its components navigating with respect to website requirements. 

React Router: Challenges and Debugging

React Router is simple to use if you follow and understand the basic template of it.  

The challenges involved when you installed it on the terminal, and tried to activate BrowserRouter but then also routing did not happen. Debugging comes with hands-on practice when you code the concept you visualize with the understanding of the concept learnt here.  

  1. Have <Link> component  inside <BrowserRouter> component because let's say if you have Header.js component with code :   

import React from 'react'; 
import { Link } from 'react-router-dom';  
const Header = () => { 
    return ( 
        <div className="App"> 
             <Link to="/" >  Home  </Link> 
             <Link to="/" >  HomePage </Link> 
        </div> 
    ); 
}; 

and App.js with the rendering looks like : 

import React from 'react'; 
import { BrowserRouter, Route, Link } from 'react-router-dom' 
import Home from "./components/Home/Home" 
import About from "./components/About/About" 
import Header from './Header'; 
const App = () => { 
  return ( 
    <div > 
      <Header /> 
      <BrowserRouter> 
        <div> 
        <Route path="/" exact component={Home} /> 
        <Route path="/about" exact component={About} /> 
        </div>  
      </BrowserRouter> 
    </div> 
  ); 
}; 
export default App;

Here Header.js is using the <Link> component in the Header.js file but <Header> is placed outside <BrowserRouter> in app.js file making the error displayed: “component that is not the child of <Router> cannot contain its components as well.  

  1. Route is the child component of Routes, it must be used like taking Routes as parent component. Here the problem lies in the react-router version installation, react router 6 version does not allow Route to render without wrapping it up in Routes parent component  just like: 

function App() { 
    return ( 
      <div> 
      <Routes> 
        <Route path="/Contact" element={<Contact />} /> 
       <Route path="/shop" element={<Shop/>} /> 
      </Routes> 
   </div> 
  ); 
 }  
  1. Do not use anchor tags instead of <Link> components because using anchor tags would not allow applications to remain Single Page Application ( SPA). HTML anchor tag would trigger a page reload or page refresh when clicked. 

  1. Use the default Route always at the end while using switch components. Default Route is in the form of Redirect or Navigate in react router-dom@6 version. 

Redirection happens when a login button is clicked on Profile page redirecting you to <Login> component. Now <Redirect> is deprecated and {useNavigate} is currently in use with react-router latest version. 

import React from "react" 
import {useNavigate} from "react-router-dom" 
  
export default function Profile() { 
   let navigate = useNavigate() 
   return ( 
   <div> 
         <h2> This is profile </h2> 
         <button> onClick ={()=>{ navigate("/about")}}> Login 
         </button> 
   </div> 
);  
  1. Routes are used rather than switch in react-router-dom@6 install  

<BrowserRouter> 
    <Routes> 
      <Route path="/" element={<Component />}> 
      </Route> 
    </Routes> 
  </BrowserRouter> 
  1. exact keyword must be used to match the components route paths precisely. If we have code somewhere like this: 

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

The problem lies here with the Home Route which is the base route. React is needed to tell other routes are also appending with the “/” using exact. 

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

How to Use React Router in Typescript

React-Router@5 is generally used for routing generally, but React-Router@6 is great for typescript programmers shipping type definitions. With packages installed react-router with typescript quick starts normally. 

  1. npm install react-router-dom 
  2. npm install @types/react-router-dom 

Typescript is an extension of JavaScript adding one good layer of safety and typing into the existing code, typing makes it easy for programmers to trace the problem. 

React Router Examples

React Router can be implemented in any case where the primary requirement is to navigate. Navbars, user Registration and Login can be implemented too. 

The segregation of components into their pages is considered to be react routing best practices. 

Step 1: Activate BrowserRouter in index.js file 

import {StrictMode } from "react"; 
import ReactDOM from "react-router-dom" 
import App from "./App" 
import {BrowserRouter as Router} from "react-router-dom" 
  
const rootElement = document.getElementById("root") 
ReactDOM.render( 
<StrictMode> 
    <BrowserRouter> 
      <App /> 
   </BrowserRouter> 
</StrictMode>, 
  rootElement 
);  

Step 2: Make different components to render on routing : Home , Wishlist , Cart, No Match. 

import React from "react" 
function Home() { 
    return ( 
       <div> 
            <h1> This is the home page </h1> 
      </div> 
    ); 
} 
export default Home; 
 
import React from "react" 
  
export default function Cart() { 
    return  <h1> This is Cart </h1> 
} 
import React from "react" 
export default function WishList() { 
 return  <h1> This is Wishlist </h1>
} 
import React from "react" 
  
export default function NoMatch() { 
    return  <h1> This is  404 </h1> 
} 

Step 3: Route them in app.js file accordingly 

import "./styles.css"; 
import {Routes , Route } from "react-router-dom"; 
import Home from "./pages/Home"; 
import Cart from "./pages/Cart"; 
import WishList from "./pages/WishList"; 
import NoMatch from "./pages/NoMatch"; 
import {Link} from "react-router-dom"; 
  
export default function App() { 
   return ( 
      <div className="App"> 
        <nav> 
            <Link to ="/"> Home </Link> || 
            <Link to ="/cart"> Cart </Link> || 
            <Link to ="/wishlist"> Wishlist </Link>  
       </nav> 
       <Routes> 
          <Route path ="/" element= {<Home />}/> 
          <Route path ="/cart" element= {<Cart />}/> 
          <Route path ="/wishlist" element= {<WishList />}/> 
          <Route path ="*" element= {<NoMatch />}/> 
       </Routes> 
  </div> 
); 
} 

The react router navbar would look like this: 

Different Types of Routers in React Router 

React Routers gives us 3 types of routing in reactJS- 

  1. Browser Router

It is the most common type and most used type of router that uses  HTML5 history API (pushState, replaceState and the popstate event) making your  UI in sync with the URL. 

  1. Hash Router

As the name sounds this type of router uses the hash portion of the URL keeping your UI in sync with the URL. 

  1. Memory Router

A router that keeps the history of your “URL” in memory does not like to put it in the  address bar. Often used but useful in testing  and non-browser environments like React Native. 

Components in React Router and their Explanation

React Router DOM in reactJS is categorized into three primary components :  

1. Routers

As we know react-router-dom is a npm package that helps in dynamic routing provides <BrowserRouter> and <HashRouter>. 

A) BrowserRouter: It is one of the parent components that is used to store all <Route> components that basically instruct the react app to navigate the components based on the route requested by the client. It is usually given an alias name ‘Router’ for ease of reference. It allows us to frame a complete and proper URL for navigation. Also, an additional point includes BrowserRouter gives us an inch of pain to handle the different routes configurations on server-side This matters when you need to deploy large-scale production apps. 

The syntax works like: 

<BrowserRouter 
       basename = {{optionalString} 
       forceRefresh={optionalBool} 
       getUserConfirmation={optionalFunc} 
       keyLength = {optionaNumber} 
> 
  <App/> 
</BrowserRouter> 
  • basenameThe basename prop is used to provide a base URL path for all the locations in the application. 
  • forceRefresh: It is a Boolean prop when set to true, refreshes and reloads the entire page with any route navigated across the same page.   
  • getUserConfirmation: A function that is used to confirm navigation but by default windows confirm it with window.confirm(). 
  • keyLength: Location is a client-side library that allows us to implement routing, each location has the unique key but by default the key length: 6  

The fundamental react router dom example is as follows: 

import "./styles.css" 
import {BrowserRouter} from "react-router-dom" 
import {Routes, Route} from "./pages/Home" 
import ProductDetail from "./pages/ProductDetail" 
export default function App( ) { 
return  
   <BrowserRouter> 
      <div className ="App"/> 
     <Routes> 
         <Route path = "/" element = {<Home />} /> 
         <Route path = "/product-detail" element = {<ProductDetail />} /> 
     </Routes> 
  </div> 
</BrowserRouter> 
) 

HashRouter: It is the same as BrowserRouter but covers the two disadvantages of it when the BrowserRouter is not able to handle some old legacy servers or static servers like GitHub Pages, then HashRouter replaces it. As the name suggests, it first and foremost adds # to the forming base URL, it is used when there is no dependency on server-side configurations. It is just a  # that is added between domain and path, and due to no dependency on history API, it works well in legacy servers. Also as it does not send anything written after # to the server request for say: https:// localhost:3000/#/about, the request will always go to / in the server, making the server happy to handle one single file only and the rest route path is handled at client side only to navigate the client to correct the route instantly.  

2. Route Matchers

They are the matchers to navigate clients to and from the correct URL   requested for using: 

a. Route: It is the most basic component that maps location to different react components to render a specific UI when the path matches the current URL. It is an alternative to an if-statement logic for saying if want to go to the requested /about the path, the route is responsible for rendering that specific component matching across the current URL like <Route path =”/about” component ={ About }/> 

<Route path ="/" component={<Home />} /> 
<Route path ="/about" component={<About />} /> 
<Route path ="/blogs" component={<Blogs />}/> 

 b. Switch: This component works similarly to the switch statement. It cuts down the exhaustive checking of each route path with the current URL instead the switch once gets the correct route path it returns back from there instead of checking till the last route path is written.    

import {BrowserRouter , Switch, Route } from "react-router-dom" 
<Switch> 
     <Route path ="/" component={<Home />} /> 
     <Route path ="/about" component={<About />} /> 
     <Route path ="/blogs" component={<Blogs />}/> 
</Switch> 
  • Route Changers : There are three types of navigators or route changers : 
  • Link: It is one of the primary ways to navigate the routes instead of putting it in the address bar you render it on UI as fully accessible just like anchor <href> tags of HTML with the main  difference of anchor tags reload the UI to navigate, but links do not reload it again 
  • NavLink: It is an extended version of Link such that it allows us to see whether the  

< Link > is active or not. This component provides isActive property that can be used with the className attribute. 

  • Redirect: It is a kind of force navigation that will redirect user to the specific page programmers want if such a route is yet not present in the application to navigate forward to. It is a substitute for 404 error pages depending on the website requirement. It exists to have a strong use-case when user signs up on any web-application he is automatically  redirected to the login page making UI experience more efficient.      
<Switch> 
      <Link to ="/home"> Home </Link> 
      <NavLink to ="about" className={({ isActive }) => 
(isActive ? 'active': 'inactive')}>About</NavLink> 
      <Route path="/" component={<Home/>} /> 
      <Route path="/about" component = {<About/>} /> 
</Switch> 

What is the Difference Between React Router and React Router DOM?

These two seem identical. react-router is the core npm package for routing, but react-router-dom is the superset of react-router providing additional components like BrowserRouter, NavLink and other components, it helps in routing for web-applications.  

Conclusion

Till now we learned the basics and fundamentals of react router and its routing mechanism to start and how it helps to render specific components on the go in web applications. The more you extend towards the application requirement the more specific use-case can be drawn from it. The crux of reactJS router works same in react router class component as well , just the syntax differences can be seen. 
Are you looking forward to learning to react from scratch? Check out the React.js certification course from KnowledgeHut, and pick the right one that best suits your interest. 

Frequently Asked Questions(FAQs)

1. Which Router is best for React JS?

Generally BrowserRouter works best for building learning projects and small scale web-applications. It is just suited less at the production level due to its unavailability in legacy servers ending it up with Cannot GET Route error plus it needs server configuration for every route created at the client side. Hence extra configuration at server side plus limitation to SPA(Single Page Application) exists.  

2. Do we need a React Router with the next JS?

Generally react-router-dom is a npm package installed for routing but nextJS has its own inbuilt router giving ease of routing with next / link using which navigation is implemented. 

3. What is the difference between router and switch?

Switch works just as the switch statement, by going through each and every route but once it matches the current URL with the route path, it returns back from there rendering that route component specifically. But Router is a standard library under which switch is a component that helps users to navigate via implementation of routing in web applications. 

4. How do I enable routing in React?

Routing in react is easily enabled while installing react-router-dom npm package and then you are good to go for ease of navigation .  

Profile

Sakshi Jain

Author

I’m Sakshi, a passionate Web Developer who is keen on learning. Coding empowers magic to my thought with the wing of programming where that thought likes to write around Web Development and programming languages domain.