VOOZH about

URL: https://www.geeksforgeeks.org/reactjs/how-to-create-custom-router-with-the-help-of-react-router/

⇱ How to Create Custom Router with the help of React Router ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

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.

Start your application using the following command.

npm start


Output:

👁 custom

Comment