Source:  Twitter logo

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>, 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() {

how can I get the current route name? To be more specific I want to get the


attribute from

<Route name="home" path="/home" handler={HomePage} />

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];

For react-router v2.0.x you can use:

17 users liked answer #0dislike answer #017
SM79 profile pic

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 }) => (
    <DocumentMeta title={ route.title } />
    <route.component {...props} routes={route.routes}/>

const matchWithSubRoutes = (key, i) => {
  const route = routes[key];
  return (<Match { ...route } key={ i } render={(props) => passPropsToRoute({ route, props })} />);

export function makeRoutes() {
  return (
      <Miss title={`${siteTitle} - Page Not Found`} component={ NotFound } />

To see this working in a example app, take a look at react-lego which has a react-router-4 branch

5 users liked answer #1dislike answer #15
peter.mouland profile pic

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.

1 users liked answer #2dislike answer #21
mp31415 profile pic

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).