Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
React router: What is it?
3.
Getting started
4.
Incorporating the React Router
4.1.
BrowserRouter
4.2.
Route
4.3.
Link
5.
Walkthrough
6.
Frequently Asked Questions
7.
Key Takeaways
Last Updated: Mar 27, 2024

Understanding React Router

Author Pratyksh
0 upvote

Introduction

Most of the modern-day websites are Single Page Applications, or more commonly referred to as SPAs. These websites are composed of a single page but look like they span over multiple pages as a result of specific components which render like separate pages.

 

It, therefore, is a no-brainer that React Router is the most popular third-party library in the React ecosystem. Here’s an interesting statistic for you:

 

React Router has been used in 44 percent of all React applications in the past six months.

 

Now that we’ve established the importance of React Router let’s explore what it has to offer and how we can utilize it to its fullest potential.

Also See, Hooks in React JS

React router: What is it?

If you're new to React, you might be surprised to learn that a router isn't built into the framework, but this is fundamental to the React ethos as React focuses solely on providing UI primitives for creating an application.

 

React Router is a declarative, component-based, client and server-side routing framework for React, released in 2014.

Unlike the traditional routing model, which handles routing in a configuration outside of a running app, dynamic routing happens as and when the app is rendering. The React router uses a component-based routing method. It offers several routing components based on the demands of the application and platform.

 

Getting started

You'll need a React web app to get started using React Router in a web app. If you don’t have one already, using the Create React App is recommended. It's a well-known tool that works nicely with React Router. 

 

To use React Router, you must first install it from the public npm registry with either npm or yarn. You'll also need to import BrowserRouter, Route, and Switch from the react-router-dom package. We’ll explore each of them in detail in the forthcoming sections.

 

Incorporating the React Router

BrowserRouter

In order to function correctly, React Router must be aware of and control your app's location. It does this through the use of its BrowserRouter component.

 

Behind the scenes, BrowserRouter makes use of the history library as well as React Context. The history library assists React Router in keeping track of the application's browsing history by utilizing the browser's built-in history stack, and React Context aids in making history available wherever React Router needs it.

 

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
document.getElementById('app))

 

From the perspective of using BrowserRouter on the web, the most vital thing to keep in 

mind is to make sure that the app is wrapped inside of the BrowserRouter component.

 

Now that we’ve learned how to enable the ReactRouter, let’s look at how to create a new route.

Route

In simple terms, Route allows you to link the location of your app to various React components.

 

<Route path='/dashboard' element={<Dashboard />} />

<Route path="/settings" element={<Settings />} />

 

Multiple routes can match on a single URL using our Route components in this configuration. You might want to do that occasionally, but most of the time, you want React Router just to render the optimal route. Fortunately, this can be easily accomplished using Routes.

 

    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/settings" element={<Settings />} />
    </Routes>

 

When you have one or more Routes, you should probably wrap them in a  Routes.

This is because it's Routes duty to comprehend all of its children's Route components and correctly pick which ones to render.

Let’s move on to how we’ll link pages together.

Link

So far, we’ve learned how to use Routes and Route to map the app's location to specific React components, and the next step is to navigate between them. The Link component serves this function.

A to prop is passed on to the Link component, determining the path the user must be directed to.

 

<nav>
  <Link to="/">Dashboard</Link>
  <Link to="/settings">Settings</Link>
</nav>

 

In order to have more control over link, a ‘to’ object can be passed. This allows you to add a query string using the search property or provide any data to the new route via the state property.

Walkthrough

 

Let’s review all the concepts we’ve discussed so far using a simple example.

We’ll make a loose resemblance to a basic landing page.

 

First, we wrap our app in the BrowserRouter element.

 

index.js

ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>
    document.getElementById('root')
)

 

Next, we add the route tags.

 

function App() {
    return (
        <main>
            <Switch>
                <Route path="/" component={Home} exact />
                <Route path="/about" component={About} />
                <Route path="/contact" component={Contact} />
            </Switch>
        </main>
    )
}

 

Now, import the components into the app. You may want to put them in a different "components" folder to keep the code tidy and understandable.

 

import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';

 

So far, our site can only be accessed by entering the URLs. To add clickable connections to the site, we utilize the React Router Link element and create a new Navbar component. 

 

function Navbar() {
  return (
    <div>
      <Link to="/">Home </Link>
      <Link to="/about">About Us </Link>
      <Link to="/shop">Shop Now </Link>
    </div>
  );
};

 

Voila! We’ve now made a single page app that can navigate around using clickable links.

Frequently Asked Questions

  1. How does the link tag work?
    Under the hood, the link tag renders an anchor tag with a real href. This also aids the people who use keyboards for navigation.

     
  2. How to decide when to use an anchor tag vs Link tag?
    If the href attribute is pointing to an external link, the use of <a> tag is recommended, but if the href points to a URL within the same app, you should use a link tag.

     

Key Takeaways

That's all there is to the fundamentals of React Router. The anchor tags are now a thing of the past. Instead, use React Router to move throughout a React project effortlessly. It's neat and tidy, and it makes adding and removing pages much more manageable.

 

If you want to learn advanced front end web development, Coding Ninjas has one of the best courses available, which you can find here.

 

Thank you for reading!

 

Live masterclass