Skip to content

Instantly share code, notes, and snippets.

@enjoylife
Forked from tim-field/useRouter.js
Created March 21, 2019 16:04
Show Gist options
  • Save enjoylife/59e4208c457ae6e7bc046e10d3275f13 to your computer and use it in GitHub Desktop.
Save enjoylife/59e4208c457ae6e7bc046e10d3275f13 to your computer and use it in GitHub Desktop.
Hooks Router & Nested relative Routes
function Parent(props) {
return (
<>
<Link to='/child'>Child</Link>
<Route path='/child' component={Child}/>
</>
);
}
function Child({match}) {
return (
<>
<Link to={`${match.url}/grandchild`}>Grandchild</Link>
<Route path={`${match.path}/grandchild`} component={Grandchild} />
</>
)
}
import { useEffect, useState } from "react"
import { createBrowserHistory } from "history"
const history = createBrowserHistory()
const trim = url => url.replace(/^\/|\/$/g, "")
function useRouter(initial = "") {
const [route, setRoute] = useState(initial)
useEffect(() => {
const { pathname, search } = new URL(route, window.location.href)
if (window.location.pathname !== pathname) {
history.push(pathname)
setRoute(trim(document.location.pathname))
} else if (window.location.search !== search) {
history.replace(pathname + search)
}
}, [route])
useEffect(() => {
window.onpopstate = function historyChange(ev) {
if (ev.type === "popstate") {
setRoute(trim(document.location.pathname))
}
}
setRoute(trim(document.location.pathname))
}, [])
return [route, setRoute]
}
export default useRouter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment