I would like to retrieve the current params outside of a component, and as far as I can tell React Router does not provide a convenient way of doing that.
Sometime back before 0.13 the router had getCurrentParams() which is what I used to use.
Now the best thing I can figure out is:
// Copy and past contents of PatternUtils into my project
var PatternUtils = require('<copy of PatternUtils.js>')
const { remainingPathname, paramNames, paramValues } =
PatternUtils.matchPattern(
"<copy of path pattern with params I am interested in>",
window.location.pathname);
Is there a way to do this with React router?
you could use matchPath:
import { matchPath } from 'react-router'
const { params }= matchPath(window.location.pathname, {
path: "<copy of path pattern with params I am interested in>"
})
If you use matchPath(window.location.pathname, ...)
within your render function, your component won't signal to be re-rendered on route changes. You can instead use react router's useLocation
hook to fix this:
import { matchPath } from 'react-router'
import { useLocation } from 'react-router-dom'
function useParams(path) {
const { pathname } = useLocation()
const match = matchPath(pathname, { path })
return match?.params || {}
}
function MyComponent() {
const { id } = useParams('/pages/:id')
return <>Updates on route change: {id}</>
}
Note: matchPath
will return null
for paths which don't match.
If you use the object destructure pattern { params } = matchPath
it may throw the following error:Cannot destructure property 'params' of 'Object(...)(...)' as it is null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With