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.
// 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')
);
// 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;
// Home.js
import React from 'react';
const Home = () => {
return (
<div>
<h2>
Welcome to Home Page
</h2>
</div>
);
}
export default Home;
// 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;
// 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:
How to Create Custom Router with the help of React Router ?
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.
Contact Us