Is there a way to expose route params outside <Route> component? Is there a way to expose route params outside <Route> component? reactjs reactjs

Is there a way to expose route params outside <Route> component?


React router will only return params if you have a path on the Route. You can pass down the params from your top level . Have that component render inside of it. It will have access to the params. As for any other time, you need to be doing:

<Route  path="/:someId" component={AnotherComponent} />

If you want it to actually get that param!

Only children underneath the Route component can access the params. You should be building your app in such a way that only the component inside that route needs its params.


You can use matchPath

import { matchPath } from 'react-router'import { useLocation } from 'react-router-dom' //----const { pathname } = useLocation()const params =  matchPath(pathname, { path:"/:someId" }) //----


You can just wrap that component with it's own Route component like this:

...  <Route path="/cameras/:camera/">  <CameraName /></Route>...// this is so the camera name can be fetched from the route.const CameraName = () => {  let { camera } = useParams();  return <div>{camera}</div>;};