Have a couple of routes with params (like. /user/:user, car/:car/:year)
I'm trying to avoid to manually parse location.pathname
if it's possible to use react-router (v3) for it.
How can I find the route that match to the current url location. Need something similar to:
if (router.match_to_route('/user/:user')) {
... do something
}
...
The method matchRoutes in .js might be the one that I need. Thanks.
Updated:
It can be achieved by
import { match } from 'react-router';
const routes = router.routes;
match({ routes, location }, (error, redirect, renderProps) => {
const listOfMatchingRoutes = renderProps.routes;
if (listOfMatchingRoutes.some(route => route.path === '/user/:user')) {
...
}
}
Have a couple of routes with params (like. /user/:user, car/:car/:year)
I'm trying to avoid to manually parse location.pathname
if it's possible to use react-router (v3) for it.
How can I find the route that match to the current url location. Need something similar to:
if (router.match_to_route('/user/:user')) {
... do something
}
...
The method matchRoutes in https://github./ReactTraining/react-router/blob/v3/modules/matchRoutes.js might be the one that I need. Thanks.
Updated:
It can be achieved by
import { match } from 'react-router';
const routes = router.routes;
match({ routes, location }, (error, redirect, renderProps) => {
const listOfMatchingRoutes = renderProps.routes;
if (listOfMatchingRoutes.some(route => route.path === '/user/:user')) {
...
}
}
https://github./ReactTraining/react-router/issues/3312#issuement-299450079
Share Improve this question edited May 6, 2017 at 19:16 DraganS asked May 5, 2017 at 1:09 DraganSDraganS 2,7091 gold badge29 silver badges43 bronze badges2 Answers
Reset to default 3I have done this using react-router-dom. I simplified the code so that you can easily understand it. I just passed the param user with my dashboard route in main App ponent and access it using this.props.match.params.user in my child ponent named as Dashboard.
App.js file
class App extends React.Component {
constructor(props) {
super(props);
this.state = {open: false};
this.state = {message: "StackOverflow"};
}
render(){
return (
<Router>
<div>
<Route exact path="/dashboard/:user" render={props => <Dashboard {...props} />} />
<Route exact path="/information" render={props => <Information {...props} />} />
</div>
</Router>
);
}
}
Dashboard.js
import React from 'react';
class Dashboard extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div ><h1> Hello {this.props.match.params.user}</h1></div>
);
}
}
export default Dashboard;
I hope it will help you.
On RR4 you can use matchPath
const match = routes.find(route) => matchPath(props.location.pathname, {
path: route.path,
exact: true,
strict: false
})