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 does React Router handle navigation in a React application?
Next article icon

Mastering React Routing: Learn Navigation and Routing in React Apps

Last Updated : 21 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

React Routing is a technique used to handle navigation within a React application. It enables users to move between different views, pages, or components without refreshing the entire page, which is a key feature of Single Page Applications (SPAs).

In this article, we will explore the essential concepts of routing in React applications. React Router provides a powerful and flexible way to handle navigation between pages in Single Page Applications (SPAs).

What is Navigation in React?

Navigation refers to the process of moving between different views or sections within a React application. In React, most applications are developed as Single Page Applications (SPA), where the entire application is loaded initially, and subsequent navigation doesn't require reloading pages from the server. Instead, routing is handled on the client side, enabling smooth transitions between different components or views without full page reloads.

To implement routing in React we do not have in-built modules but instead, we use the react-router-dom module after installing and importing it.

Syntax

// Installing npm i react-router-dom // Importing import { BrowserRouter } from 'react-router-dom';
  • Installing: npm i react-router-dom installs React Router for routing in React.
  • Importing: import { BrowserRouter } from 'react-router-dom'; imports BrowserRouter to enable routing in your app.

Programmatically Navigate in React

Programmatic navigation allows you to navigate between different routes based on actions, such as button clicks or form submissions. This method provides more control over routing, enabling navigation in response to events triggered by the user.

Approach

  • Create 2 basic pages between which you want to redirect
  • Create buttons on each page to redirect the user
  • Import the useNavigate hook provided with react-router-dom
  • Use this hook on the onClick event button to redirect
JavaScript
// App.js  import { BrowserRouter, Routes, Route } from "react-router-dom"; import "./App.css"; import AboutUs from "./components/AboutUs"; import ContactUs from "./components/CotactUs";  function App() {     return (         <div className="App">             <BrowserRouter>                 <Routes>                     <Route exact path="/" element={<AboutUs />} />                     <Route exact path="/contactus" element={<ContactUs />} />                 </Routes>             </BrowserRouter>         </div>     ); }  export default App; 
JavaScript
// AboutUs.js  import React from "react"; import { useNavigate } from "react-router-dom";  function AboutUs() {     const nav = useNavigate();     return (         <div>             <h2>GeeksforGeeks is a computer science portal for geeks!</h2>             Read more about us at :             <a href="https://www.geeksforgeeks.org/about/">                 https://www.geeksforgeeks.org/about/             </a>             <br></br>             <br></br>             <button                 onClick={() => {                     nav("contactus");                 }}             >                 Click Here to check contact details             </button>         </div>     ); } export default AboutUs; 
JavaScript
// ContactUs.js  import React from "react"; import { useNavigate } from "react-router-dom";  function ContactUs() {     const nav = useNavigate();     return (         <div>             <address>                 You can find us here:                 <br />                 GeeksforGeeks                 <br />                 5th & 6th Floor, Royal Kapsons, A- 118, <br />                 Sector- 136, Noida, Uttar Pradesh (201305)             </address>             <br></br>             <br></br>             <button                 onClick={() => {                     nav(-1);                 }}             >                 Click Here to Go Back             </button>         </div>     ); }  export default ContactUs; 

Output

gfg

In this example

  • App.js: This file displays the AboutUs component.
  • AboutUs.js: This components creates the link to Contact Us page using Button.
  • ContactUs.js: This component has a button to send back to previous page.

Dynamic Routing with React router

Adding Link routes gets very lengthy when there are multiple pages, so we use the concept of Dynamic Routing to reduce the lines of code and make the code shorter. Dynamic routing allows you to define routes dynamically based on certain conditions.

Approach

  • Create a page which will create Link components using map
  • Create a page which will display data dynamically using useParams
  • Create a dynamic Route component which passes the id as a parameter
JavaScript
// App.js  import { BrowserRouter, Routes, Route, Link } from "react-router-dom"; import CourseDetails from "./components/CourseDetails";  function App() {     const courses = ["JavaScript", "React", "HTML", "DSA"];     return (         <BrowserRouter>             <h1>Dynamic Routing with React</h1>             <ul>                 {courses.map((course) => {                     return (                         <li key={course}>                             <Link to={`courses/${course}`}>{course}</Link>                         </li>                     );                 })}             </ul>             <Routes>                 <Route path="courses/:courseId" element={<CourseDetails />} />             </Routes>         </BrowserRouter>     ); }  export default App; 
JavaScript
// components/CourseDetails.js  import { useParams } from "react-router-dom";  function CourseDetails() {     const { courseId } = useParams();     return (         <div>             <h1>This is {courseId} course</h1>         </div>     ); }  export default CourseDetails; 

Output

gfg

In this code

  • App.js: This file creates Link component dynamically and sends course name as a parameter
  • CourseDetails.js: This file accesses the course as a parameter and passes it.

Handling 404 Errors (Page Not Found)

Sometimes user types a URL which does not exist in the website and the router fails and shows an error. To solve this problem we create a universal Route component which redirects to Link not found page whenever incorrect URL is passed.

Approach

  • Create 3 basic pages where you want to add navigation
  • Create a Navbar to handle navigation between the pages
  • Create NoPageFound.js file to handle routing for all incorrect routing
  • Add a path for non-configured routes which will be redirected to NoPageFound file
  • the path with '*' handles all non-configured routes
JavaScript
// App.js  import logo from "./logo.svg"; import { BrowserRouter, Routes, Route } from "react-router-dom"; import "./App.css"; import NavBar from "./components/Navbar"; import Home from "./components/Home"; import AboutUs from "./components/AboutUs"; import ContactUs from "./components/CotactUs"; import NoPageFound from "./components/NoPageFound";  function App() {     return (         <div className="App">             <BrowserRouter>                 <NavBar />                 <Routes>                     <Route exact path="/" element={<Home />} />                     <Route exact path="/about" element={<AboutUs />} />                     <Route exact path="/contact" element={<ContactUs />} />                     <Route path="*" element={<NoPageFound />} />                 </Routes>             </BrowserRouter>         </div>     ); }  export default App; 
JavaScript
// AboutUs.js import React from "react";  function AboutUs() {     return (         <div>             <h2>GeeksforGeeks is a computer science portal for geeks!</h2>             Read more about us at :             <a href="https://www.geeksforgeeks.org/about/">                 https://www.geeksforgeeks.org/about/             </a>         </div>     ); } export default AboutUs; 
JavaScript
// ContactUs.js import React from "react";  function ContactUs() {     return (         <address>             You can find us here:             <br />             GeeksforGeeks             <br />             5th & 6th Floor, Royal Kapsons, A- 118, <br />             Sector- 136, Noida, Uttar Pradesh (201305)         </address>     ); }  export default ContactUs; 
JavaScript
// Home.js import React from "react";  function Home() {     return <h1>Welcome to the world of Geeks!</h1>; }  export default Home; 
JavaScript
// Navbar.js  import { Link } from "react-router-dom";  export default function NavBar() {     return (         <div>             <ul className="r">                 <li>                     <Link to="/">Home</Link>                 </li>                 <li>                     <Link to="/about">About Us</Link>                 </li>                 <li>                     <Link to="/contact">Contact Us</Link>                 </li>             </ul>         </div>     ); } 
JavaScript
// NoPageFound.js  export default function NoPageFound() {     return <h1>Error 404: Page Not Found</h1>; } 

Output

In this code

  • App.js: This file imports all the components and applies routing to them
  • AboutUs.js: This file contains the About Us Page
  • ContactUs.js: This file displays the Contact Us Page
  • Home.js: This component acts as the home page
  • Navbar.js: This component has the Navbar to redirect to all linking pages
  • NoPageFound.js: This page is displayed when invalid links are added.

Conclusion

Learning navigation and routing in React is essential for building smooth, interactive web applications. React Router makes it easy to manage navigation between different pages or views without reloading the page, helping you create seamless single-page applications. By understanding how to set up basic routes, work with dynamic paths, navigate programmatically, and use nested routes, you can build more efficient and user-friendly React apps that offer a smooth browsing experience for users.


Next Article
How does React Router handle navigation in a React application?

S

shobhit__sharma
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • ReactJS-Router

Similar Reads

  • How to Use Routing with React Navigation in React Native ?
    Almost every mobile application requires navigating between different screens. React Native provides an elegant and easy-to-use library to add navigation to native applications: react-navigation. It is one of the most popular libraries used for routing and navigating in a React Native application. T
    4 min read
  • How does React Router handle navigation in a React application?
    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. Let us create a simple application to React to understand how the React Router works Re
    3 min read
  • Create Store Navigation using React and Tailwind CSS
    We will build a simple Store Navigation system using React and Tailwind CSS and React Icons. The navigation bar will have links to different store sections such as Home and Products and Cart and Profile. Each link will be styled with icons accompanying them to make the UI more intuitive. We will als
    5 min read
  • Create a basic Navbar using React Router v6
    React Router is a library for handling routing and navigation in React JS Applications. It allows you to create dynamic routes, providing a seamless user experience by mapping various URLs to components. It enables navigation in a single-page application (SPA) without refreshing the entire page. Rea
    5 min read
  • What is Routing and Nested Routing in Angular 9/8 ?
    In this article, we will learn the routing & nested routing concept in Angular. We will implement the concept to establish routing between different components by making their routes when a user clicks the link, it will be navigated to a page link corresponding to the required component. Let's u
    5 min read
  • Implementing React Router with Redux in React
    This article explores implementing React Router with Redux for enhanced state management and routing in React applications. Table of Content What is React Router and Redux?Approach to implement React Router in ReduxSteps to Setup the React AppWhat is React Router and Redux?React Router facilitates r
    3 min read
  • ReactJS UI Ant Design Navigation Component Complete Reference
    Ant Design is a popular ReactJS UI library that is used to build the design system for enterprise-level products. The Ant Design contains a rich set of high-quality components for building efficient & interactive user interfaces with an enjoyable work experience. Ant design facilitates a huge nu
    1 min read
  • How to create Breadcrumb Navigation Using React ?
    Breadcrumbs are useful in navigation and provide users with links representing their path through a website or application. In this tutorial, we'll create a simple e-commerce website with product listings and detail pages, incorporating breadcrumbs for a better user experience. Output Preview: Let u
    6 min read
  • How to add navigation links to the React Bootstrap Navbar?
    In ReactJS, we use Nabvar or Navigation Bar as the core component. For ease of navigation over the application, we use this NavBar in react-bootstrap. We need to add navigation links to go through different routes or pages of the application. So to add the navigation links to the React Bootstrap Nav
    5 min read
  • Navigate Component in React Router
    In React applications, navigation between different pages or views is an essential part of creating dynamic user interfaces. React Router is a popular library used for handling routing and navigation. One of the key features of React Router is the Navigate component, which allows for programmatic re
    7 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