Implementing React Router without react-router-dom: A Famous Interview Question in React
React Router DOM is a popular library used for implementing routing in React applications. However, in some cases, you may not want to use an external library for routing. In this blog post, we will explore how to implement React routing without using React Router DOM.
First, let's take a look at the code:
import React, { useState, useEffect } from 'react';
import { Home } from './components/Home';
import { Contact } from './components/Contact'
import {About} from './components/About'
const routingTable = {
'/': Home,
'/about': About,
'/contact': Contact,
};
const Router = () => {
const [currentUrl, setCurrentUrl] = useState(window.location.pathname);
const handleUrlChange = () => {
setCurrentUrl(window.location.pathname);
};
useEffect(() => {
window.addEventListener('popstate', handleUrlChange);
return () => {
window.removeEventListener('popstate', handleUrlChange);
};
}, []);
const CurrentComponent = routingTable[currentUrl];
return <CurrentComponent />;
};
const App = () => {
return (
<div>
<Router />
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
</div>
);
};
export default App;
In this code, we have defined a routing table as an object, where each key represents a URL and each value represents a component. For example, the URL "/" is mapped to the Home component.
We have also defined a Router component, which is responsible for rendering the correct component based on the current URL. It does this by using the useState and useEffect hooks to keep track of the current URL, and by using the routing table to determine which component to render.
Finally, we have defined our main App component, which renders the Router component and a navigation menu with links to the different routes.
So how does this work? When a user clicks on a link in the navigation menu, the browser will navigate to the corresponding URL. This triggers a popstate event, which we listen for in the useEffect hook of the Router component. When this event occurs, we update the current URL state using the handleUrlChange function.
The Router component then uses the routing table to determine which component to render based on the current URL. We use the bracket notation to access the value in the routing table that matches the current URL.
And that's it! With just a few lines of code, we have implemented basic routing in our React application without using React Router DOM. Of course, this approach has its limitations and may not be suitable for more complex applications. However, for simple applications, it can be a useful alternative to using an external routing library.
what is popstate event ?
The popstate
event is an event that is fired in JavaScript when the user navigates through their browsing history, such as when they use the back or forward buttons. This event is associated with the window
object and can be used to handle changes to the browser's history.
Here is an example code snippet that demonstrates the use of the popstate
event:
window.addEventListener('popstate', function(event) {
console.log('Location changed to:', window.location.href);
});
In this code, we add an event listener to the window
object that listens for the popstate
event. When the event is fired (i.e., when the user navigates through their history), the function passed to the event listener will be executed. In this case, the function logs the new URL to the console using console.log()
.