19

If I have something like this:

<ConnectedRouter history={history}>
    <App />
</ConnectedRouter>

My routes config looks like:

export default [{
    path: '/',
    exact: true,
    main: Home
}, 
{
    path: '/:someId',
    exact: true,
    main: Profile
},
{
    path: '*',
    main: NotFound
}];

Where app is just a wrapper of the routes and other components like:

class App extends Component {
render() {
return (
  <div>
    <Header />
    <Switch>
      {routes.map((route, i) => <Route exact key={i} component={route.main} path={route.path}/>)}
    </Switch>
    <AnotherComponent {...this.props} />
  </div>
);
}
}

Is there a way for AnotherComponent to use match.params or to expose those? I already tried wrapping the component with withRouter and also adding it as a Route with no path to match like:

<Route component={AnotherComponent} />

And when the route is /:someId it does render both Profile and AnotherComponent, but match.params for AnotherComponent are empty :/.

Is this possible? Thanks!

gl0gl0
  • 255
  • 3
  • 7

3 Answers3

7

Edit: You can use https://v5.reactrouter.com/web/api/Hooks/useroutematch directly these days.

Original Answer

You can use matchPath

import { matchPath } from 'react-router'
import { useLocation } from 'react-router-dom'

 //----
const { pathname } = useLocation()

const params =  matchPath(pathname, { path:"/:someId" })
 //----

Haseeb A
  • 5,356
  • 1
  • 30
  • 34
1

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.

zackify
  • 5,314
  • 2
  • 22
  • 28
  • 5
    I understand, the problem is that I need this component to be always present. At first is "hidden" but when navigating to /:someId, I need to initialize it with the information of this id, and then have it actively present throughout the app, even if the route changes. – gl0gl0 Jun 27 '17 at 15:22
  • 1
    Then render it with a question mark at the end :) `` That will render it with or without that id! – zackify Jun 28 '17 at 13:41
  • Perfect! Thank you! – gl0gl0 Jun 28 '17 at 22:18
-1

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>;
};
TacoEater
  • 2,115
  • 20
  • 22