Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
How to setup ReactJs with Vite ?
Next article icon

How to setup React Router v6 ?

Last Updated : 02 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

React Router is an amazing library that was created by Remix. The purpose of React Router is to enable Client-Side routing in the React application, that is, by using React Router we can create different routes in our React app and can easily navigate to different pages without even reloading the page.

Client-side routing, facilitated by React Router, enables changing routes without page reloads, creating single-page applications (SPAs). React Router efficiently manages what is displayed on each route, making it a powerful and user-friendly library for seamless navigation in React applications.

We will discuss the following setup approach and different methods of React Router v6 in this article:

Table of Content

  • Approach to setup React Router in Application
  • Steps to set up React Router
  • Implementation of React Router v6
  • Nested Routes
  • useNavigate()
  • DynamicRoutes:
  • createRoutesFromElements:

Approach to setup React Router in Application

  • NavBar.js: Utilizes the Link tag instead of an anchor tag for navigation without page reloads. Ensures the website remains a single-page application.
  • index.js: Uses createBrowserRouter to establish routes: "/" (Home), "/home" (About), "/contact" (Contact). Wraps components needing routing in RouterProvider with the created router.
  • App.js: Renders NavBar and the Outlet component provided by React Router. Outlet dynamically displays content based on the current route.

Steps to set up React Router

Step 1: Create a react project folder, open the terminal, and write the following command.

# Run this to use npm
npx create-react-app foldername
# Or run this to use yarn
yarn create react-app foldername

Step 2: Navigate to the root directory of your project using the following command.

cd foldername

Step 3: Now, install the React Router library

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

Project Structure

Screenshot30
Project Structure

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
"react-router-dom": "^6.22.0"
}

Implementation of React Router v6:

Example: Below is the code to create the navbar and routes.

CSS
/* App.css */  nav {     background-color: #333;     padding: 10px; }  ul {     list-style-type: none;     margin: 0;     padding: 0; }  li {     display: inline;     margin-right: 20px; }  a {     text-decoration: none;     color: white; }  a:hover {     color: lightgray; } 
JavaScript
// NavBar.js import { Link } from 'react-router-dom';   const Navbar = () => { 	return ( 		<nav> 			<ul> 				<li><Link to="/">Home</Link></li> 				<li><Link to="/about">About</Link></li> 				<li><Link to="/contact">Contact</Link></li> 			</ul> 		</nav> 	); }  export default Navbar; 
JavaScript
// index.js import React from 'react' import ReactDOM from 'react-dom/client'  import { 	RouterProvider, 	createBrowserRouter } from 'react-router-dom'  import App from './App' import Home from './Home' import About from './About' import Contact from './Contact'  const router = createBrowserRouter([ 	{ 		path: '/', 		element: <App />, 		children: [ 			{ 				path: '/', 				element: <Home />, 			}, 			{ 				path: '/about', 				element: <About />, 			}, 			{ 				path: '/contact', 				element: <Contact />, 			}, 		] 	} ]);  ReactDOM.createRoot(document.getElementById('root')).render( 	<RouterProvider router={router}> 		<App /> 	</RouterProvider> ) 
JavaScript
// App.js import { Outlet } from 'react-router-dom'; import './App.css' import NavBar from "./NavBar";  const App = () => { 	return ( 		<> 			<NavBar /> 			<Outlet /> 		</> 	); }  export default App; 
JavaScript
// Home.js import React from 'react'  const Home = () => { 	return ( 		<div>Home</div> 	) }  export default Home 
JavaScript
// About.js import React from 'react'  const About = () => { 	return ( 		<div>About</div> 	) }  export default About 
JavaScript
// Contact.js import React from 'react'  const Contact = () => { 	return ( 		<div>Contact</div> 	) }  export default Contact 

Start your application using the following command.

npm start

Output:

Nested Routes:

Nested routes means routes within routes. For example, the About page can have two links, one link for About company and one link for About founder of the company.

We will have to create routes something like these.

"/about/about-founder"
"/about/about-company"

This is what nested routes are. So creating nested routes is very simple, as you have already created a route for about, you have to add children array to it.
Example 2: Below is an example of nested routes.

JavaScript
// About.js  import { Outlet, useNavigate } from "react-router-dom"  const About = () => { const navigate = useNavigate(); return ( 	<div> 	<button onClick={() => navigate("about-founder")}>About - Founder</button> 	<button onClick={() => navigate("about-company")}>About - Company</button>  	<Outlet /> 	</div> ) }  export default About 
JavaScript
// index.js  import React from 'react' import ReactDOM from 'react-dom/client' import App from './App' import { RouterProvider, createBrowserRouter } from 'react-router-dom' import Home from './Home' import About from './About' import Contact from './Contact' import Founder from './Founder' import Company from './Company'  const router = createBrowserRouter([ { 	path: '/', 	element: <App />, 	children: [ 	{ 		path: '/', 		element: <Home />, 	}, 	{ 		path: '/about', 		element: <About />, 		children: [ 		{ 			path: "about-founder", 			element: <Founder /> 		}, 		{ 			path: "about-company", 			element: <Company /> 		} 		] 	}, 	{ 		path: '/contact', 		element: <Contact />, 	}, 	] } ]);  ReactDOM.createRoot(document.getElementById('root')).render( 	<React.StrictMode> 	<RouterProvider router={router}> 		<App /> 	</RouterProvider> 	</React.StrictMode> ) 
JavaScript
import React from 'react'  const Founder = () => { 	return ( 		<div>Founder</div> 	) }  export default Founder 
JavaScript
import React from 'react'  const Company = () => { 	return ( 		<div>Comapny</div> 	) }  export default Company 

Output:

gfg66
Output

useNavigate():

This is a hook given by React Router. useNavigate returns a function, and using this function we can navigate anywhere. You just need to enter the path where you want to navigate. That's all there was to nested routes, now you can create routes at any depth. Now let's see how to create dynamic routes.

DynamicRoutes:

Let us first understand what dynamic routes are. Dynamic route means the route that we did not know before. They are created dynamically based on any variable or parameter and are non-static and numbers can reach thousands and millions.

for example, this youtube video link:

https://youtube.com/watch/[some video id]

Now this video ID will be different for every video. So such routes are dynamic routes.

To set up dynamic routes, let's take an example. Suppose there are many contacts in the contact page and each contact has a unique ID. We will just use this unique ID and create pages for all contacts with just one route.

We can write a path like this

path: "/contact/:id"


Example 3: Look at the below code for a better understanding

JavaScript
// ContactCard.js import { useParams } from "react-router-dom"  const ContactCard = () => { 	const { id } = useParams(); 	return ( 		<h1>Contact id: {id}</h1> 	) }  export default ContactCard 
JavaScript
// index.js  import React from 'react' import ReactDOM from 'react-dom/client' import App from './App' import { RouterProvider, createBrowserRouter } from 'react-router-dom' import Home from './Home' import About from './About' import Contact from './Contact' import Founder from './Founder' import Company from './Company' import ContactCard from './ContactCard'  const router = createBrowserRouter([ 	{ 		path: '/', 		element: <App />, 		children: [ 			{ 				path: '/', 				element: <Home />, 			}, 			{ 				path: '/about', 				element: <About />, 				children: [ 					{ 						path: "about-founder", 						element: <Founder /> 					}, 					{ 						path: "about-company", 						element: <Company /> 					} 				] 			}, 			{ 				path: '/contact', 				element: <Contact />, 			}, 			{ 				path: "/contact/:id", 				element: <ContactCard /> 			} 		] 	} ]);  ReactDOM.createRoot(document.getElementById('root')).render( 	<React.StrictMode> 		<RouterProvider router={router}> 			<App /> 		</RouterProvider> 	</React.StrictMode> ) 

Output:

createRoutesFromElements:

If you do not like the syntax to create routes from these objects then we can also use a different syntax. To do this, we will call another function in createBrowserRouter which is createRoutesFromElements and in this function, we will set up the routes.

import {
RouterProvider,
createBrowserRouter,
createRoutesFromElements,
Route,
} from "react-router-dom";

const router = createBrowserRouter(
createRoutesFromElements(
<Route path="/" element={<App />}>
<Route path="/" element={<Home />} />
\\Other Route
</Route>
)
);

Next Article
How to setup ReactJs with Vite ?
author
tapeshdua420
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • ReactJS-Router

Similar Reads

  • Migrate to React Router v6
    React Router v6 brings significant changes and improvements over its predecessor, offering a more intuitive API and better performance. Migrating to React Router v6 might seem daunting, but with proper guidance, the transition can be smooth and beneficial for your React applications. Enhancements in
    3 min read
  • How to setup 404 page in React Routing?
    When you're building a React app with routing, it's important to handle cases where users land on a page that doesn't exist. A 404 page is a good way to inform users that the page they’re looking for cannot be found. Prerequisites:NPM & Node JSReact JSReact-router-domApproach to Set Up a 404 Pag
    4 min read
  • React Router Tutorial
    React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL. With React Router, you can create a single-page application (SPA) with multiple "pages"
    3 min read
  • useRoutes Hook in React Router
    React Router is a library that is used for handling navigation and routing in React applications. It provides a way to navigate between different components or pages while maintaining a single-page application (SPA) structure. One of the key features is the useRoutes hook. It allows you to define ro
    4 min read
  • How to setup ReactJs with Vite ?
    Vite is a fast and modern build tool for creating web applications. It increases the development process by providing faster build times and better performance. Some of the benefits of using React with Vite are mentioned below: Fast updates without page reloads.Faster and smaller production builds.A
    3 min read
  • React Router V5 vs V6
    React Router is widely appreciated in React apps for handling routing and navigation. It provides a way to configure routes. Show components based on the current URL. The newest release, React Router v6 introduces changes and improvements compared to the version of React Router v5. This article will
    7 min read
  • React-Router Hooks
    React-Router is a popular React library that is heavily used for client-side routing and offers single-page routing. It provides various Component APIs( like Route, Link, Switch, etc.) that you can use in your React application to render different components based on the URL pathnames on a single pa
    11 min read
  • React JS Types of Routers
    When creating a React application, managing navigation between different views or pages is important. React Router is the standard library for routing in React, enabling seamless navigation while maintaining the Single Page Application (SPA) behaviour. What is React Router?React Router is a declarat
    10 min read
  • React Router vs. React Router DOM
    Routing is a fundamental part of any web application. It allows users to move between pages or views. smoothly in traditional web development Routing involves mapping URLs to specific content or views on the server. These are the following topics that we are going to discuss: Table of Content What i
    4 min read
  • How to use TypeScript with React?
    TypeScript enhances JavaScript by adding strict type definitions, making your code more robust and maintainable. ReactJS, a popular library for building user interfaces, pairs excellently with TypeScript to create clean, efficient, and scalable codebases. Combining TypeScript with React offers a pow
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences