Created
August 25, 2022 08:22
-
-
Save ZacharyL2/9fe178cfa14e80e4d29c7873f7431d98 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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