As on subject how can I get the route name inside the handler? For example:
var routes = <Route handler={App} path="/">
<Route name="home" path="/home" handler={HomePage} />
<DefaultRoute handler={HomePage} />
</Route>
Router.run(routes, function(Handler, state) {
var params = state.params;
React.render(<Handler params={params}/>, document.body);
});
Now suppose I have a component like this:
class HomePage extends React.Component {
render() {
return(<div>MyComponent</div>)
}
}
how can I get the current route name? To be more specific I want to get the
name="home"
attribute from
<Route name="home" path="/home" handler={HomePage} />
Use the useLocation() hook to get the current route with React Router, e.g. const location = useLocation() . The hook returns the current location object. For example, you can access the pathname as location.
Before react-router 0.13 you can use this.getRoutes()
using Router.State
mixin.
For react-router 0.13 you can use this too:
var currentRoutes = this.context.router.getCurrentRoutes();
var lastRoute = currentRoutes[currentRoutes.length - 1];
console.log(lastRoute.name);
For react-router v2.0.x you can use:
this.props.routes[this.props.routes.length-1]
v4 has removed the JS API from the code base which means the above methods won't work moving forward.
The new way is to actually pass the props directly to the component being rendered, just like you normally would with any other component in you React app.
import React from 'react';
import { Match, Link, Miss } from 'react-router';
import DocumentMeta from 'react-document-meta';
import MainLayout from './Layouts/MainLayout';
import Homepage from './containers/Homepage/Homepage';
import Game from './containers/Game/Game';
import NotFound from './containers/NotFound/NotFound';
export const routes = {
homepage: {
exactly: true,
pattern: '/',
label: 'About React Lego',
component: Homepage
},
game: {
pattern: '/game',
label: 'Star Wars Trivia',
component: Game
}
};
const passPropsToRoute = ({ route, props }) => (
<span>
<DocumentMeta title={ route.title } />
<route.component {...props} routes={route.routes}/>
</span>
);
const matchWithSubRoutes = (key, i) => {
const route = routes[key];
return (<Match { ...route } key={ i } render={(props) => passPropsToRoute({ route, props })} />);
};
export function makeRoutes() {
return (
<MainLayout>
{Object.keys(routes).map(matchWithSubRoutes)}
<Miss title={`${siteTitle} - Page Not Found`} component={ NotFound } />
</MainLayout>
);
}
To see this working in a example app, take a look at react-lego which has a react-router-4 branch
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