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 Integrate React Router with Remix?
Next article icon

How to Create Custom Router with the help of React Router ?

Last Updated : 18 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To create a custom Router using React Router, you can define a new component that utilizes the Router's 'BrowserRouter' along with 'Route' components to handle different paths and render corresponding components. Use 'Link' components for navigation within your application, providing a seamless routing experience in your React application.

What is a React Router?

React Router is a popular library for implementing routing in React applications. It allows developers to manage navigation and rendering of components in response to browser URL changes. React Router enables the creation of single-page applications (SPAs) by providing declarative routing capabilities within the React ecosystem.

Steps to Create React App And Installing React Router:

Step 1: Create a New React Project: Set up a new React project using

npx create-react-app my-react-app

Step 2: Navigate to Your Project Directory

cd my-react-app

Step 3: Install following modules

npm install react react-router-dom

Project Structure:

Screenshot-2024-03-12-231845

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

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.3",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Approach to create Custom Router using React Router:

  • First define the routes in the main App component using React Router.
  • Using Links for navigation between different routes.
  • Creating a CustomRouter component that utilizes React Router's useLocation hook to track the current path and render the corresponding component based on the route path.
  • Using useEffect hook to update the current path state when the location changes.

Example: This example shows implementation to create a custom router.

JavaScript
// index.js  import React from 'react'; import ReactDOM from 'react-dom'; import App from './App';  ReactDOM.render(     <React.StrictMode>         <App />     </React.StrictMode>,     document.getElementById('root') ); 
JavaScript
// App.js  import React from 'react'; import { BrowserRouter as Router, Link } from 'react-router-dom'; import Home from './Components/Home'; import About from './Components/About'; import CustomRouter from './Components/CustomRouter';  const App = () => {     const routes = [         { path: '/', component: Home },         { path: '/about', component: About }     ];      return (         <Router>             <div>                 <nav>                     <ul>                         <li>                             <Link to="/">Home</Link>                         </li>                         <li>                             <Link to="/about">About</Link>                         </li>                     </ul>                 </nav>                 <hr />                 <h1>Custom Router Example</h1>                 <CustomRouter initialPath=                     {window.location.pathname} routes={routes} />             </div>         </Router>     ); };  export default App; 
JavaScript
// Home.js  import React from 'react';  const Home = () => {     return (         <div>             <h2>                 Welcome to Home Page             </h2>         </div>     ); }  export default Home; 
JavaScript
// About.js  import React from 'react';  const About = () => {     return (         <div>             <h2>About Us</h2>             <p>                 This is the About page.             </p>         </div>     ); }  export default About; 
JavaScript
// CustomRouter.js  import React, { useState, useEffect } from 'react'; import { useLocation } from 'react-router-dom';  const CustomRouter = ({ routes }) => {     const location = useLocation();     const [currentPath, setCurrentPath] =         useState('');      useEffect(() => {         setCurrentPath(location.pathname);     }, [location]);      const RouteComponent =         routes.find(route => route.path === currentPath)?.component;      return RouteComponent ? <RouteComponent /> : null; };  export default CustomRouter; 

Start your application using the following command.

npm start


Output:

custom


Next Article
How to Integrate React Router with Remix?

R

rituali8i63
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-Questions
  • ReactJS-Router

Similar Reads

  • How to Create a Protected Route with react-router-dom?
    A protected route in a React application is a route that only authorized users can access. This is useful for securing parts of an application that should not be available to everyone. We will see how we can create a protected route with react-router-dom. Prerequisites:NPM & NodeJSReactJSSteps t
    3 min read
  • How to Read the Current full URL with React?
    In React applications, it is often necessary to read the current full URL for various purposes, such as routing, conditional rendering, or logging. There are two common approaches to achieve this: using the window.location object and using the useLocation hook from react-router-dom. Prerequisites:NP
    3 min read
  • What are the React Router hooks in React v5?
    React Router hooks perform client-side single-page routing that provides a functional and streamlined approach to managing navigation in React applications. It provides a way to directly access the state of the router from functional components, this simplifies tasks like retrieving information abou
    5 min read
  • How to Create Store in React Redux ?
    React Redux is a JavaScript library that is used to create and maintain state in React Applications efficiently. Here React Redux solves the problem by creating a redux store that stores the state and provides methods to use the state inside any component directly or to manipulate the state in a def
    4 min read
  • How to Integrate React Router with Remix?
    Integrating React Router with Remix includes the usage of Remix's integrated router abilities thinking that Remix already uses React Router as its foundation. However, if you want to go beyond number one routing and leverage several React Router's extra precise or advanced skills. You may integrate
    7 min read
  • How to handle Nested Routes in React Router ?
    React Router allows us to create a hierarchical structure where child components can be rendered within parent components, resulting in a seamless navigation flow. In this article, we will see how to handle nested Routes in React Router. Approach to handle Nested RoutesTo implement nested routes in
    3 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
  • Route Component in React Router
    React Router is a popular library used for managing routing in React applications. At its core lies the Route component, which plays a pivotal role in defining the relationship between URLs and corresponding components. In this article, we'll delve into the intricacies of the Route component, explor
    5 min read
  • How to Create Multiple Routes in the Same Express.js Server ?
    Creating multiple routes in an Express.js server involves defining routes in separate modules. This modular approach allows for better organization and maintainability by managing different routes independently and mounting them in the main server file. ApproachTo create multiple routes in an Expres
    2 min read
  • Routes Component in React Router
    Routes are an integral part of React Router, facilitating the navigation and rendering of components based on URL patterns. In this article, we'll delve into the concept of routes, understanding their role in React Router, and how to define and manage routes effectively. Table of Content What are Ro
    4 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