React Routing in Plain React

import React from 'react';
import { useEffect, useState } from 'react';

window.addEventListener("click", function (event) {
const link = event.target.closest("a");
if (
!event.button &&
!event.altKey &&
!event.ctrlKey &&
!event.metaKey &&
!event.shiftKey &&
link &&
link.href.startsWith(window.location.origin + "/") &&
link.target !== "_blank"
) {
event.preventDefault();
navigate(link.href);
}
});

export default function Router ({routes, defaultComponent}) {

const [currentPath, setCurrentPath] = useState(window.location.pathname);

useEffect(() => {
const onLocationChange = () => {
setCurrentPath(window.location.pathname);
}

window.addEventListener('popstate', onLocationChange);

return () => {
window.removeEventListener('popstate', onLocationChange)
};
}, [])
return routes.find(({path, component}) => path === currentPath)?.component || defaultComponent
}


export function navigate (href) {

// update url
window.history.pushState({}, "", href);

// communicate to Routes that URL has changed
const navEvent = new PopStateEvent('popstate');
window.dispatchEvent(navEvent);
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ashok Khanna

Ashok Khanna

Masters in Quantitative Finance. Writing Computer Science articles and notes on topics that interest me, with a tendency towards writing about Lisp & Swift