Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get params outside of a component

Tags:

react-router

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?

like image 763
misterwilliam Avatar asked Feb 02 '16 17:02

misterwilliam


2 Answers

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>"
})
like image 138
Peter Riesz Avatar answered Oct 23 '22 00:10

Peter Riesz


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.

like image 40
alecdwm Avatar answered Oct 22 '22 23:10

alecdwm