Skip to content

Instantly share code, notes, and snippets.

@ZacharyL2
Created August 25, 2022 08:22
Show Gist options
  • Save ZacharyL2/9fe178cfa14e80e4d29c7873f7431d98 to your computer and use it in GitHub Desktop.
Save ZacharyL2/9fe178cfa14e80e4d29c7873f7431d98 to your computer and use it in GitHub Desktop.
import { useEffect, useState } from 'react';
const 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((route) => route.path === currentPath)
?.component ?? defaultComponent
);
};
export const navigate = (href) => {
window.history.pushState(null, '', href);
const navEvent = new PopStateEvent('popstate');
window.dispatchEvent(navEvent);
};
export default Router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment