Last active
December 27, 2022 07:36
-
-
Save gragland/8322804ba43392d5a1e96d37d1a38218 to your computer and use it in GitHub Desktop.
React Hook recipe from https://usehooks.com
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 { useMemo } from "react"; | |
import { useParams, useLocation, useHistory, useRouteMatch } from 'react-router-dom'; | |
import queryString from 'query-string'; | |
// Usage | |
function MyComponent(){ | |
// Get the router object | |
const router = useRouter(); | |
// Get value from query string (?postId=123) or route param (/:postId) | |
console.log(router.query.postId); | |
// Get current pathname | |
console.log(router.pathname) | |
// Navigate with with router.push() | |
return ( | |
<button onClick={(e) => router.push('/about')}>About</button> | |
); | |
} | |
// Hook | |
export function useRouter() { | |
const params = useParams(); | |
const location = useLocation(); | |
const history = useHistory(); | |
const match = useRouteMatch(); | |
// Return our custom router object | |
// Memoize so that a new object is only returned if something changes | |
return useMemo(() => { | |
return { | |
// For convenience add push(), replace(), pathname at top level | |
push: history.push, | |
replace: history.replace, | |
pathname: location.pathname, | |
// Merge params and parsed query string into single "query" object | |
// so that they can be used interchangeably. | |
// Example: /:topic?sort=popular -> { topic: "react", sort: "popular" } | |
query: { | |
...queryString.parse(location.search), // Convert string to object | |
...params | |
}, | |
// Include match, location, history objects so we have | |
// access to extra React Router functionality if needed. | |
match, | |
location, | |
history | |
}; | |
}, [params, match, location, history]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@gragland I updated the hook with the react-router-dom latest version 6.