How to get route name in handler using react-route?
react-router 4
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
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]
Assuming we are talking about the same react-router (and the current version is 2.8.x) you can access the route directly via this.props.route.path
, which will be /home
for your home page (in HomePage
component).
Link to the docs.
Edit: link updated.