Guvi-blog-logo

How to setup React Router v6? | Tutorial 2023

React Router

Are you looking to learn how to set up React Router v6 and start routing your React applications? This guide will show you step-by-step how to get up and running with React Router v6 and start building dynamic, single-page applications. With React Router v6, you can create powerful and dynamic routing solutions with ease. You’ll learn how to set up routes, define components, and customize your routes with dynamic parameters. Let’s get started!

React Router v6.4.0 is a library for routing in React applications. It provides a routing solution that allows developers to declaratively map routes to components, and manage the URL and navigation state of the application. It also provides features like route preloading, lazy loading, and query params.

Routing allows the user to navigate through different pages of your app without refreshing the whole page. With the help of routing, you can create a single-page application (SPA) that allows the users to navigate through different pages of your web app without refreshing the whole page and improve the overall user experience by making your application faster, more responsive and more dynamic.

Step-by-Step Guide to React Router

Follow the setup instructions carefully to add an easy navigation feature to your React app with different pages.

Step 1: Installing React Router 

To install React Router, you’ll need Node.js installed for the npm command line tool and after which you have to run the following command:

npm install react-router-dom

and wait for the installation to complete. 

If you are using Yarn then run the following command: 

yarn add react-router-dom

Step 2: Adding React Router 

The first thing to do after installation of react-router-dom is to make React Router available anywhere in your app. For this we use a <BrowserRouter> that stores the current location in the browser’s address bar using clean URLs and navigates using the browser’s built-in history stack.

To do this, open the index.js file in the src folder and replace the <React.StrictMode> with <BrowserRouter> by importing it from react-router-dom and then wrapping the root component in it. 

index.js file before changes:


import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

reportWebVitals();

index.js file after changes:


import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

reportWebVitals();

So, now you can access all the features of react-router-dom like routers, routes, etc.

Step 3: Routing and Rendering components

1. Creating Multiple components

To render different components for routing, we’ll create some components in our project. In your project src folder, create a new folder as Pages. In that, create some components such as Home.js, Courses.js, Live.js, and Contact.js.

See the code of all the components below:

Home.js

import React from 'react'

function Home() {
  return (
    <div>Home</div>
  )
}

export default Home

Contact.js

import React from 'react'

function Contact() {
  return (
    <div>Contact</div>
  )
}

export default Contact

Courses.js

import React from 'react'

function Courses() {
  return (
    <div>Courses</div>
  )
}

export default Courses

Live.js

import React from 'react'

function Live() {
  return (
    <div>Live</div>
  )
}

export default Live

After creating all the component files, the project directory should look like this:

2. Define routes

Our root component is the App.js component where our React code gets rendered from initially, we will be creating all our routes in it. 

To define the routes, we are going to use two things: Routes and Route. Import both the components from react-router-dom and use them to route the components. The syntax for defining the routes is as follows:

<Routes>
   <Route path="/" element={<Home />} />
   <Route path="/course" element={<Courses />} />
   <Route path="/live" element={<Live />} />
   <Route path="/contact" element={<Contact />} />
</Routes>

Let’s understand this syntax in detail:

  • <Routes>- The <Routes> component is used to define the different routes that are available in your application. Each individual route is defined using a <Route> component.
  • <Route>- The <Route> component takes in a path prop, which is a string that defines the URL path that the route should match.
  • path- The path prop defines the route path. 
  • element- The component prop defines the React component to render when the route path matches the current URL.

3. Link to navigate to components

Now we will use the <Link> component of react-router-dom to create clickable links that change the URL of the browser and render a different component based on the new URL.

This component takes in a to prop, which is a string that defines the URL path that the link should navigate to and when the user clicks on a <Link> component, the URL of the browser will change to the path specified in the to prop, and the appropriate component associated with that route will be rendered. 

In our example, we have defined a route with a path prop of ‘/contact’, therefore we can create a <Link> component with a to prop of ‘/contact’ to allow the user to navigate to the contact page. The same procedure goes for all of the components to navigate through the different pages. 

We will now use <Link> to navigate to different pages based on the routes and pathnames we have defined in the App component as shown below:

import "./App.css";
import React from "react";
import { Link } from "react-router-dom";

import Home from "../src/Pages/Home";
import Courses from "../src/Pages/Courses";
import Live from "../src/Pages/Live";
import Contact from "../src/Pages/Contact";

function App() {
  return (
      <nav>
        <ul>
          <Link to="/" class="list">
            Home
          </Link>
          <Link to="/course" class="list">
            Courses
          </Link>
          <Link to="/live" class="list">
            Live course
          </Link>
          <Link to="/contact" class="list">
            Contact
          </Link>
        </ul>
      </nav>
  );
}

export default App;

Final Code

If you followed and coded along with us through the blog, then your App.js file should look like this:

import "./App.css";
import React from "react";
import { Link, Route, Routes } from "react-router-dom";

import Home from "../src/Pages/Home";
import Courses from "../src/Pages/Courses";
import Live from "../src/Pages/Live";
import Contact from "../src/Pages/Contact";

function App() {
  return (
    <div className="container">
      <nav>
        <ul>
          <Link to="/" class="list">
            Home
          </Link>
          <Link to="/course" class="list">
            Courses
          </Link>
          <Link to="/live" class="list">
            Live course
          </Link>
          <Link to="/contact" class="list">
            Contact
          </Link>
        </ul>
      </nav>

      {/* Defining routes path and rendering components as element */}
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/course" element={<Courses />} />
        <Route path="/live" element={<Live />} />
        <Route path="/contact" element={<Contact />} />
      </Routes>
    </div>
  );
}

export default App;

Output

React Router v6

Conclusion

Setting up React Router in your application is a straightforward process that can greatly enhance the user experience of your app. With React Router, you can easily define and manage routes, and create clickable links that change the URL without refreshing the whole page.

At this point, you have seen how to install, set up and use React Router to navigate to different pages in your web application. Not only this, but you also saw how routing works and rendered the components in react.

By following these simple steps, you can add powerful routing functionality to your React application, allowing the users to easily navigate through different pages of your web app. Hope you learned a lot from this blog but don’t stop learning here!

Are you interested in Building an Application using React?

Learn to Build an App using React in just 90 days through Zen Class Career Program & Become a Full-stack Developer with 100% Job Placement Support.

Are you ready to take your coding skills to the next level? Then join our Full Stack Development Bootcamp by Zen Class and become a master in the art of full stack. We’ll teach you the latest technologies and best practices to help you become a full-stack developer.

Our comprehensive course will cover HTML, CSS, JavaScript, React, Node.js, MongoDB, and more. With our expert instructor, mentors from product-based companies, and hands-on real-world projects, you’ll be able to build dynamic web applications and take your coding career to the next level. 

Sign up today and unleash your coding potential!

Contact Form

By clicking 'Submit' you Agree to Guvi Terms & Conditions.

Our Learners Work at

Our Popular Course

Share this post

Author Bio

Tarun Singh
Tarun Singh
Tarun Singh is a Front-End Developer and Technical Writer with 2+ years of relevant experience. He is passionate about creating appealing and user-friendly apps and in writing technical articles. His expertise lies in ReactJS.

Our Live Classes

Learn Javascript, HTML, CSS, Java, Data Structure, MongoDB & more
Learn Python, Machine Learning, NLP, Tableau, PowerBI & more
Learn Selenium, Python, Java, Jenkins, Jmeter, API Testing & more

UX Processes, Design systems, Responsive UI, & more with placement assistance.

Hey wait, Don’t miss New Updates from GUVI!

Get Your Course Now

Related Articles