-
-
Save enjoylife/59e4208c457ae6e7bc046e10d3275f13 to your computer and use it in GitHub Desktop.
Hooks Router & Nested relative Routes
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
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} /> | |
</> | |
) | |
} |
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" | |
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