React Router is a complete routing solution designed specifically for React.js. It painlessly synchronizes the components of your application with the URL, with first-class support for nesting, transitions, and server side rendering.

Contribute on Github.

OverviewGuides

To illustrate the problems React Router is going to solve for you, let’s build a small application without it.

Without React Router

var About = React.createClass({/*...*/});
var Inbox = React.createClass({/*...*/});
var Home = React.createClass({/*...*/});

var App = React.createClass({
  getInitialState () {
    return {
      route: window.location.hash.substr(1)
    };
  },

  componentDidMount () {
    window.addEventListener('hashchange', () => {
      this.setState({
        route: window.location.hash.substr(1)
      });
    });
  },

  render () {
    var Child;
    switch (this.props.route) {
      case 'about': Child = About; break;
      case 'inbox': Child = Inbox; break;
      default:      Child = Home;
    }

    return (
      <div>
        <h1>App</h1>
        <Child/>
      </div>
    )
  }
});

React.render(<App />, document.body);

As the hash portion of the URL changes, App will render a different <Child/> by branching on this.state.route. Pretty straightforward stuff. But it gets complicated fast.

Imagine now that Inbox has some nested UI at a path like inbox/messages/:id and inbox/unread, etc. We'll need to make our url parsing much more intelligent to be able to pass the right information to App, and then to Inbox in order for it to know which URL-mapped child component it should render. We'd then have a branch of components that should be rendered at any given URL. Add a few more of these branches and we'll end up with a lot of code to keep the URL and our application's component hierarchy in sync.

With React Router

Nested URLs and nested component hierarchy are at the heart of React Router. It brings a declarative API to your routes. Lots of people like to use JSX to define their routes, but you can use plain objects if you want.

Let's refactor our app to use React Router.

// first we import some components
import { Root, Route } from 'react-router';

// ...

// then we delete a bunch of code from `App`
var App = React.createClass({
  render () {
    return (
      <div>
        <h1>App</h1>
        {/*
          next we replace `<Child>` with `this.props.children`
          the router will figure out the children for us
        */}
        {this.props.children}
      </div>
    )
  }
});

// Finally we render a `Root` component with some `Route`s, it'll do all
// the fancy routing stuff for us.
React.render((
  <Root>
    <Route path="/" component={App}>
      <Route path="about" component={About}/>
      <Route path="inbox" component={Inbox}/>
    </Route>
  </Root>
), document.body);

If you're not digging the JSX route config you can use plain objects:

var routes = {
  path: '/',
  component: App,
  childRoute: [
    { path: 'about', component: About },
    { path: 'inbox', component: Inbox },
  ]
};

React.render(<Root children={routes}/>, document.body):

Adding more UI

Alright, now we're ready to nest the inbox messages inside the inbox UI.

// Make a new component to render inside of Inbox
var Message = React.createClass({
  render () {
    return <h3>Message</h3>;
  }
});

var Inbox = React.createClass({
  render () {
    return (
      <div>
        <h2>Inbox</h2>
        {/* Render the child route component */}
        {this.props.children || "Welcome to your Inbox"}
      </div>
    );
  }
});


React.render((
  <Root>
    <Route component={App}>
      <Route path="about" component={About}/>
      <Route path="inbox" component={Inbox}>
        {/* Add the route, nested where we want the UI to nest */}
        <Route path="messages/:id" component={Message}/>
      </Route>
    </Route>
  </Root>
), document.body);

Now visits to urls like inbox/messages/Jkei3c32 will match the new route and nest the UI branch of App -> Inbox -> Message.

Getting the url parameters

We're going to need to know something about the message in order to fetch it from the server. Route components get some useful properties injected into them when you render, particularly the parameters from the dynamic segment of your path. In our case, :id.

var Message = React.createClass({
  componentDidMount: function () {
    // from the path `/inbox/messages/:id`
    var id = this.props.params.id;
    fetchMessage(id, function (err, message) {
      this.setState({ message: message });
    })
  },
  // ...
});

That's the gist of React Router. Application UIs are boxes inside of boxes inside of boxes; now you can keep those boxes in sync with the URL.

Advanced UsageGuides

React Router is great for small sites like React.js Training ("React Router brought to you by ...") but its built with websites like facebook and twitter in mind, too.

The biggest concern for large apps is the amount of JavaScript required to boot the app. Large apps should download only the JavaScript required to render the current view. Some people call this "code splitting", you split your code up into multiple bundles that are loaded on-demand as the visitor navigates around.

Its important that changes deep down in the application don't require changes all the way up top. Adding a route to the photo viewer should not affect the size of the initial JavaScript bundle the user downloads. Neither should it cause merge conflicts as multiple teams have their fingers in the same, big route configuration file.

Your router is the perfect place to handle code splitting: its responsible for setting up your views.

React Router does all of its path matching and component resolving asynchronously, which allows you to not only load up the components lazily, but also lazily load the route configuration. You really only need one route definition in your initial bundle, the router will resolve the rest on demand.

Routes can define getChildRoutes and getComponents methods. These are asynchronous and only called when needed. We call it "gradual matching". React Router will gradually match the url and fetch only the amount of route configuration and components it needs to match the path and render.

Coupled with webpack's built-in code splitting, a once tireless architecture is now simple and declarative, look at this route:

module.exports = {
  path: 'course/:courseId',

  getChildRoutes (cb) {
    require.ensure([
      './routes/Announcements',
      './routes/Assignments',
      './routes/Grades',
    ], (require) => {
      cb(null, [
        require('./routes/Announcements'),
        require('./routes/Assignments'),
        require('./routes/Grades'),
      ])
    })
  },

  getComponents (cb) {
    require.ensure(['./components/Course'], (require) => {
      cb(null, require('./components/Course'))
    })
  }
};

Now go look at what hacks you have in place to do this. Just kidding, I don't want to make you sad right now.

It's also really easy to imagine some tooling that auto-generates a route like this from your file system.

Check out the huge apps example in the repository. Even better, open your web inspector and watch code get loaded in as you navigate around the demo.

Server RenderingGuides

To illustrate the problems React Router is going to solve for you, let’s build a small application without it.

Without React Router

var About = React.createClass({
  render: function () {
    return <h2>About</h2>;
  }
});

var Inbox = React.createClass({
  render: function () {
    return <h2>Inbox</h2>;
  }
});

var Home = React.createClass({
  render: function () {
    return <h2>Home</h2>;
  }
});

var App = React.createClass({
  getInitialState () {
    return {
      route: window.location.hash.substr(1)
    };
  },

  componentDidMount () {
    window.addEventListener('hashchange', () => {
      this.setState({
        route: window.location.hash.substr(1)
      });
    });
  },

  render () {
    var Child;
    switch (this.state.route) {
      case 'about': Child = About; break;
      case 'inbox': Child = Inbox; break;
      default:      Child = Home;
    }

    return (
      <div>
        <h1>App</h1>
        <Child/>
      </div>
    )
  }
});

React.render(<App/>, document.body);

As the hash portion of the URL changes, App will render a different <Child/> by branching on this.state.route. Pretty straightforward stuff. But it gets complicated fast.

Imagine now that Inbox has some nested UI at a path like inbox/messages/:id and inbox/unread, etc. We'll need to make our url parsing much more intelligent to be able to pass the right information to App, and then to Inbox in order for it to know which URL-mapped child component it should render. We'd then have a branch of components that should be rendered at any given URL. Add a few more of these branches and we'll end up with a lot of code to keep the URL and our application's component hierarchy in sync.

With React Router

Nested URLs and nested component hierarchy are at the heart of React Router. Lets make our routing for our little app declarative. Lots of people like the look of JSX for route configuration since its a great way to describe hierarchy and properties, but you can use plain objects too.

import { Root, Route } from 'react-router';

// First we need to delete some code from `App`. We'll replace `<Child/>`
// with `{this.props.children}` that functions as the old `switch` block from
// before. The router is going to set that up for us now.

var App = React.createClass({
  render () {
    return (
      <div>
        <h1>App</h1>
        {this.props.children}
      </div>
    )
  }
});

// Then we render a `Root` component with the Routes as children.

React.render((
  <Root>
    <Route component={App}>
      <Route path="about" component={About}/>
      <Route path="inbox" component={Inbox}/>
    </Route>
  </Root>
), document.body);

If you're not into the JSX route config, you can use plain objects, the props are all the same. (this is what React Router turns them into anyway).

var routes = {
  component: App,
  childRoutes: [
    { path: 'about', component: About },
    { path: 'inbox', component: Inbox }
  ]
};

React.render(<Root routes={routes}/>, document.body);

Adding more UI

Alright, now we're ready to nest the inbox messages inside the inbox UI.

// First we'll make a new `Message` component to render at our new route
var Message = React.createClass({
  render () {
    return <h3>Message</h3>;
  }
});

var Inbox = React.createClass({
  render: function () {
    return (
      <div>
        <h2>Inbox</h2>
        {/* Next we render the child route component */}
        {this.props.children || "Welcome to your Inbox"}
      </div>
    );
  }
});

React.render((
  <Root>
    <Route component={App}>
      <Route path="about" component={About}/>
      <Route path="inbox" component={Inbox}>
        {/* finally we nest the route */}
        <Route path="messages/:id" component={Message}/>
      </Route>
    </Route>
  </Root>
), document.body);

Now visits to urls like inbox/messages/Jkei3c32 will match the new route and nest the UI branch of App -> Inbox -> Message. While your app maybe end up with complex nesting, putting it all together is always this simple with React Router.

Getting the url parameters

We're going to need to know something about the message in order to fetch it from the server. We call the component you hand to a <Route/> a "Route Component". These components get some useful properties injected into them when you render, particularly the parameters from the dynamic segment of your path. In our case, :id.

var Message = React.createClass({
  componentDidMount: function () {
    // from the path `/inbox/messages/:id`
    var id = this.props.params.id;
    fetchMessage(id, function (err, message) {
      this.setState({ message: message });
    })
  },
  // ...
});

That's the gist of React Router. Application UIs are boxes inside of boxes inside of boxes; now you can keep those boxes in sync with the URL effortlessly.

TestingGuides

To illustrate the problems React Router is going to solve for you, let’s build a small application without it.

Without React Router

var About = React.createClass({
  render: function () {
    return <h2>About</h2>;
  }
});

var Inbox = React.createClass({
  render: function () {
    return <h2>Inbox</h2>;
  }
});

var Home = React.createClass({
  render: function () {
    return <h2>Home</h2>;
  }
});

var App = React.createClass({
  render () {
    var Child;
    switch (this.props.route) {
      case 'about': Child = About; break;
      case 'inbox': Child = Inbox; break;
      default:      Child = Home;
    }

    return (
      <div>
        <h1>App</h1>
        <Child/>
      </div>
    )
  }
});

function render () {
  var route = window.location.hash.substr(1);
  React.render(<App route={route} />, document.body);
}

window.addEventListener('hashchange', render);
render(); // render initially

As the hash portion of the URL changes, App will render a different <Child/> by branching on this.props.route. Pretty straightforward stuff. But it gets complicated fast.

Imagine now that Inbox has some nested UI at a path like inbox/messages/:id and inbox/unread, etc. We'll need to make our url parsing much more intelligent to be able to pass the right information to App, and then to Inbox in order for it to know which URL-mapped child component it should render. We'd then have a branch of components that should be rendered at any given URL. Add a few more of these branches and we'll end up with a lot of code to keep the URL and our application's component hierarchy in sync.

With React Router

Nested URLs and nested component hierarchy are at the heart of React Router. Lets make our routing for our little app declarative. We use JSX for route configuration because we want to define a view hierarchy with properties, so its a pefect fit.

var Router = require('react-router');
var Route = Router.Route;

// declare our routes and their hierarchy
var routes = (
  <Route handler={App}>
    <Route path="about" handler={About}/>
    <Route path="inbox" handler={Inbox}/>
  </Route>
);

Next we need to delete some code from App. We'll replace <Child/> with <RouteHandler/> that functions as the old switch block from before.

var RouteHandler = Router.RouteHandler;

var App = React.createClass({
  render () {
    return (
      <div>
        <h1>App</h1>
        <RouteHandler/>
      </div>
    )
  }
});

Finally we need to listen to the url and render the application.

Router.run(routes, Router.HashLocation, (Root) => {
  React.render(<Root/>, document.body);
});

Root is a component that bakes in the matched component hierarchy making RouteHandler know what to render.

Note that <Route/> components are not ever rendered, they are just configuration objects that the router uses to create an internal tree of routes.

Adding more UI

Alright, now we're ready to nest the inbox messages inside the inbox UI. First we'll make a new Message component and then we'll add the route under inbox so that the UI will nest.

var Message = React.createClass({
  render () {
    return <h3>Message</h3>;
  }
});

var routes = (
  <Route handler={App}>
    <Route path="about" handler={About}/>
    <Route path="inbox" handler={Inbox}>
      <Route path="messages/:id" handler={Message}/>
    </Route>
  </Route>
);

Now visits to urls like inbox/messages/Jkei3c32 will match the new route and nest the UI branch of App -> Inbox -> Message.

Getting the url parameters

We're going to need to know something about the message in order to fetch it from the server. We call the component you hand to a <Route/> a RouteHandler. RouteHandler instances get some useful properties injected into them when you render, particularly the parameters from the dynamic segment of your path. In our case, :id.

var Message = React.createClass({
  componentDidMount: function () {
    // from the path `/inbox/messages/:id`
    var id = this.props.params.id;
    fetchMessage(id, function (err, message) {
      this.setState({ message: message });
    })
  },
  // ...
});

Nested UI and Nested URLs need not be coupled

With React Router, you don't need to nest your UI in order to get a nested URL. Inversely, to get nested UI, you don't need to have nested URLs either.

Lets make a new url at /about/company, but without nesting the UI inside of the About component.

var routes = (
  <Route handler={App}>
    <Route path="about" handler={About}/>
    <Route path="about/company" handler={Company}/>
  </Route>
);

Though our url is nested, the UI of About and Company are siblings.

Now lets go the other way and add the url /archive/messages/:id and have it nested under our inbox UI even though the URL is not nested. We have to do three things for this to work:

  1. Start the path with / to signal that its an absolute path. This won’t “inherit” the parent path the way inbox/messages/:id gets inherited.
  2. Nest the <Route/> under the inbox route to cause the UI to nest.
  3. Ensure you have all the necessary dynamic segments, we only have :id so its pretty easy.
var routes = (
  <Route handler={App}>
    <Route path="inbox" handler={Inbox}>
      <Route path="messages/:id" handler={Message}/>
      <Route path="/archive/messages/:id" handler={Message}/>
    </Route>
  </Route>
);

That's the gist of React Router. Application UIs are boxes inside of boxes inside of boxes; now you can keep those boxes in sync with the URL.

RedirectRoute Configuration

A Redirect sets up a redirect to another route in your application to maintain old URLs.

Props

from

The path you want to redirect from, including dynamic segments. Defaults to * so you can redirect anything not found to somewhere else.

to

The name of the route you want to redirect to.

params

By default, the parameters will just pass through to the new route, but you can specify them if you need to (usually you shouldn't).

query

By default, the query parameters will just pass through to the new route, but you can specify them if you need to (usually you shouldn't).

Example

<!--
  lets say we want to change from `/profile/123` to `/about/123`
  and redirect `/get-in-touch` to `/contact`
-->
<Route handler={App}>
  <Route name="contact" handler={Contact}/>
  <Route name="about-user" path="about/:userId" handler={UserProfile}/>
  <Route name="course" path="course/:courseId">
    <Route name="course-dashboard" path="dashboard" handler={Dashboard}/>
    <Route name="course-assignments" path="assignments" handler={Assignments}/>
  </Route>

  <!-- `/get-in-touch` -> `/contact` -->
  <Redirect from="get-in-touch" to="contact" />

  <!-- `/profile/123` -> `/about/123` -->
  <Redirect from="profile/:userId" to="about-user" />

  <!-- `/profile/me` -> `/about-user/123` -->
  <Redirect from="profile/me" to="about-user" params={{userId: SESSION.USER_ID}} />
</Route>

Note that the <Redirect/> can be placed anywhere in the route hierarchy, if you'd prefer the redirects to be next to their respective routes, the from path will match the same as a regular route path.

<Route handler={App}>
  <Route name="course" path="course/:courseId">
    <Route name="course-dashboard" path="dashboard" handler={Dashboard}/>
    <!-- /course/123/home -> /course/123/dashboard -->
    <Redirect from="home" to="course-dashboard" />
  </Route>
</Route>

RouteRoute Configuration

A Route is used to declaratively map routes to your application's screen hiearchy.

Props

name (optional)

The unique name of the route, used in the Link component and the router's transition methods.

path (optional)

The path used in the URL. If left undefined, the path will be defined by the name, and if there is no name, will default to /.

Please refer to the Path Matching Guide to learn more about supported path matching syntax.

handler

The RouteHandler component to be rendered when the route is active.

children

Routes can be nested. When a child route path matches, the parent route is also activated. Please refer to the overview since this is a very critical part of the router's design.

ignoreScrollBehavior

When a route or its params change, the router adjusts window scroll position according to the [scrollBehavior][scrollbehavior]. This is generally desirable but you might want to opt-out of scrolling adjustment for a specific route or a group of routes.

If you specify ignoreScrollBehavior, changes in params or any transitions within its children will not adjust scroll position. This can be useful on a search page or in a tabbed interface.

Note that changes in query never adjust scroll position, regardless of the value of this attribute.

Example

<!-- `path` defaults to '/' since no name or path provided -->
<Route handler={App}>
  <!-- path is automatically assigned to the name since it is omitted -->
  <Route name="about" handler={About}/>
  <Route name="users" handler={Users}>
    <!--
      note the dynamic segment in the path, and that it starts with `/`,
      which makes it "absolute", or rather, it doesn't inherit the path
      from the parent route
    -->
    <Route name="user" handler={User} path="/user/:id"/>
  </Route>
</Route>

AdvancedRoute Configuration

A Route is used to declaratively map routes to your application's screen hiearchy.

Props

name (optional)

The unique name of the route, used in the Link component and the router's transition methods.

path (optional)

The path used in the URL. If left undefined, the path will be defined by the name, and if there is no name, will default to /.

Please refer to the Path Matching Guide to learn more about supported path matching syntax.

handler

The RouteHandler component to be rendered when the route is active.

children

Routes can be nested. When a child route path matches, the parent route is also activated. Please refer to the overview since this is a very critical part of the router's design.

ignoreScrollBehavior

When a route or its params change, the router adjusts window scroll position according to the [scrollBehavior][scrollbehavior]. This is generally desirable but you might want to opt-out of scrolling adjustment for a specific route or a group of routes.

If you specify ignoreScrollBehavior, changes in params or any transitions within its children will not adjust scroll position. This can be useful on a search page or in a tabbed interface.

Note that changes in query never adjust scroll position, regardless of the value of this attribute.

Example

<!-- `path` defaults to '/' since no name or path provided -->
<Route handler={App}>
  <!-- path is automatically assigned to the name since it is omitted -->
  <Route name="about" handler={About}/>
  <Route name="users" handler={Users}>
    <!--
      note the dynamic segment in the path, and that it starts with `/`,
      which makes it "absolute", or rather, it doesn't inherit the path
      from the parent route
    -->
    <Route name="user" handler={User} path="/user/:id"/>
  </Route>
</Route>

LinkComponents

The primary way to allow users to navigate around your application. Link will render a fully accesible anchor tag with the proper href.

A Link also knows when the route it links to is active and automatically applies its activeClassName and/or activeStyle when it is.

Props

href

The path to link to, ie /users/123.

query

An object of key:value pairs to be stingified by your history.

activeClassName

The className a Link receives when its route is active. Defaults to active.

activeStyle

The styles to apply to the link element when its route is active.

onClick

A custom handler for the click event. Works just like a handler on an <a> tag - calling e.preventDefault() or returning false will prevent the transition from firing, while e.stopPropagation() will prevent the event from bubbling.

others

You can also pass props you'd like to be on the <a> such as a title, id, className, etc.

Example

Given a route like <Route path="/users/:userId"/>:

<Link to={`/users/${user.id}`}>{user.name}</Link>
// becomes one of these depending on your History and if the route is
// active
<a href="/users/123" class="active">Michael</a>
<a href="#/users/123">Michael</a>

// change the activeClassName
<Link to={`/users/${user.id}`} activeClassName="current">{user.name}</Link>

// change style when link is active
<Link to="/users" style={{color: 'white'}} activeStyle={{color: 'red'}}>Users</Link>

Route ComponentComponents

A user-defined component given to a Route as the component prop. The router will inject properties into your component when its rendered.

Injected Props

children

The matched child route elements to be rendered.

Example

const routes = (
  <Route component={App}>
    <Route path="groups" components={Groups}}/>
    <Route path="users" components={Users}}/>
  </Route>
);

const App = React.createClass({
  render () {
    return (
      <div>
        {/* this will be either <Users> or <Groups> */}
        {this.props.children}
      </div>
    );
  }
});

Named Children

When a route has multiple components, the elements are available by name on props. All route components can participate in the nesting.

Example

const routes = (
  <Route component={App}>
    <Route path="groups" components={{main: Groups, sidebar: GroupsSidebar}}/>
    <Route path="users" components={{main: Users, sidebar: UsersSidebar}}>
      <Route path="users/:userId" components={Profile}/>
    </Route>
  </Route>
);

const App = React.createClass({
  render () {
    // the matched child route components become props in the parent
    return (
      <div>
        <div className="Main">
          {this.props.main}
        </div>
        <div className="Sidebar">
          {this.props.sidebar}
        </div>
      </div>
    );
  }
});

const Users = React.createClass({
  render () {
    return (
      <div>
        {/* if at "/users/123" this will be <Profile> */}
        {/* UsersSidebar will also get <Profile> as this.props.children */}
        {this.props.children}
      </div>
    );
  }
});

params

The dynamic segments of the url.

query

The query parameters of the url.

location

The location matched.

route

The matched Route the component belongs to.

Examples

// given a route like this:
<Route path="/course/:courseId/students" component={Students}/>

// and a url like this:
"/course/123/students?sort=name"

var Students = React.createClass({
  render () {
    this.props.params.courseId; // "123"
    this.props.query.sort; // "name"
    this.props.location; // { path: "/course/123/students?sort=name" }
    // ...
  }
});

RouterComponents

Renders a branch of route components given a location.

Props

Generally you do not need to provide any props to Router. It should be used as a direct child of a History component, which will automatically inject the location prop it needs and then Router will match the location to the routes and manage all the state it needs to render.

However, there are cases where you need to provide Router with that state manually.

On the server you want to fetch data before rendering, and typically you want Router to help you decide what to fetch. However, Router determines its state after render, which is too late for server rendering. React Router provides a match function that calculates the state you need before rendering, then you pass it in as props.

For testing, you can simply render Router with stubbed props representing the state you want to test.

location

A location from a History or a string path for server rendering and testing.

params

An object of the names/values that correspond with dynamic segments in your route path.

branch

An array of matched routes for a location.

components

An array of route components from the route branch.

children

A single Middleware child.

Examples

Typical Usage

import { Router, BrowserHistory } from 'react-router';
import routes from './routes';
React.render((
  <BrowserHistory>
    <Router routes={routes}/>
  </BrowserHistory>
));

With Middleware

import { Router, BrowserHistory } from 'react-router';
import routes from './routes';

React.render((
  <BrowserHistory>
    <Router routes={routes}>
      <Transitions>
        <RestoreScroll/>
      </Transitions>
    </Router>
  </BrowserHistory>
));

Server Rendering

import { match, Router } from 'react-router';
import routes from './routes';

someServer((req, res) => {
  match(req.path, routes, (err, props) => {
    // props contains location, params, branch, components,
    // useful for loading up some data, you could get queries from your
    // matched components, etc.
    loadData(props, (err, data) => {
      // pass in the props and `Router` will use them for initial state
      var markup = React.renderToString(<Router {...props} routes={routes}/>);
    });
  });
});

Testing

Just stub all the props and make your assertions. Though, you're really just testing Router, a component React Router already tests. You should probably just test your components.

it('does stuff', () => {
  var stubs = {
    location: '/friends/sally',
    params: { friendName: 'sally' },
    branch: [
      { component: App },
      { path: '/friends/:name', component: Friend }
    ]
    components: [App, Friend]
  };
  var subject = <Router routes={routes} {...stubs}/>;
  expect(subject).toBeAwesome();
});

NavigationMixins

A mixin for components that need to create URLs and/or initiate transitions to other routes.

Instance Methods

transitionTo(routeNameOrPath, [params[, query]])

Programmatically transition to a new route.

Examples

this.transitionTo('user', {id: 10}, {showAge: true});
this.transitionTo('about');
this.transitionTo('/users/10?showAge=true');
this.transitionTo('http://example.com/users/10?showAge=true');

replaceWith(routeNameOrPath, [params[, query]])

Programmatically replace current route with a new route. Does not add an entry into the browser history.

Examples

this.replaceWith('user', {id: 10}, {showAge: true});
this.replaceWith('about');
this.replaceWith('/users/10?showAge=true');

goBack()

Programmatically go back to the last route and remove the most recent entry from the browser history.

Example

this.goBack();

makePath(routeName, params, query)

Creates a URL path to a route.

makeHref(routeName, params, query)

Creates an href to a route. Use this along with State when you need to build components similar to Link.

Example

// given a route like this:
// <Route name="user" path="users/:userId"/>
this.makeHref('user', {userId: 123}); // "users/123"

Example

var Navigation = require('react-router').Navigation;

React.createClass({
  mixins: [Navigation],

  render: function() {
    return (
      <div onClick={() => this.transitionTo('foo')}>Go to foo</div>
      <div onClick={() => this.replaceWith('bar')}>Go to bar without creating a new history entry</div>
      <div onClick={() => this.goBack()}>Go back</div>
    );
  }
});

StateMixins

A mixin for components that need to know about the active params, query and routes. Any handler on a route with dynamic segments will want to use this.

Instance Methods

getPath()

Returns the current URL path, including query string.

getPathname()

Returns the current URL path without the query string.

getParams()

Returns a hash of the currently active URL params.

getQuery()

Returns a hash of the currently active query params.

isActive(routeName, params, query)

Returns true if a route, params, and query are active, false otherwise.

getRoutes()

Returns an array of the currently active routes, in nesting order.

Examples

Usually you'll just want access to params and query:

// route
<Route name="user" path="user/:name" handler={User} />

// handler
var User = React.createClass({
  mixins: [ Router.State ],

  render: function () {
    var name = this.getParams().name;
    return (
      <div>
        <h1>{name}</h1>
      </div>
    );
  }
});

Let's say you are using bootstrap and want to get active on those li tags for the Tabs:

var Link = require('react-router').Link;
var State = require('react-router').State;

var Tab = React.createClass({

  mixins: [ State ],

  render: function () {
    var isActive = this.isActive(this.props.to, this.props.params, this.props.query);
    var className = isActive ? 'active' : '';
    var link = (
      <Link {...this.props} />
    );
    return <li className={className}>{link}</li>;
  }

});

// use it just like <Link/>, and you'll get an anchor wrapped in an `li`
// with an automatic `active` class on both.
<Tab to="foo">Foo</Tab>

TransitionHookMixins

A mixin for components that need to know about the active params, query and routes. Any handler on a route with dynamic segments will want to use this.

Instance Methods

getPath()

Returns the current URL path, including query string.

getPathname()

Returns the current URL path without the query string.

getParams()

Returns a hash of the currently active URL params.

getQuery()

Returns a hash of the currently active query params.

isActive(routeName, params, query)

Returns true if a route, params, and query are active, false otherwise.

getRoutes()

Returns an array of the currently active routes, in nesting order.

Examples

Usually you'll just want access to params and query:

// route
<Route name="user" path="user/:name" handler={User} />

// handler
var User = React.createClass({
  mixins: [ Router.State ],

  render: function () {
    var name = this.getParams().name;
    return (
      <div>
        <h1>{name}</h1>
      </div>
    );
  }
});

Let's say you are using bootstrap and want to get active on those li tags for the Tabs:

var Link = require('react-router').Link;
var State = require('react-router').State;

var Tab = React.createClass({

  mixins: [ State ],

  render: function () {
    var isActive = this.isActive(this.props.to, this.props.params, this.props.query);
    var className = isActive ? 'active' : '';
    var link = (
      <Link {...this.props} />
    );
    return <li className={className}>{link}</li>;
  }

});

// use it just like <Link/>, and you'll get an anchor wrapped in an `li`
// with an automatic `active` class on both.
<Tab to="foo">Foo</Tab>

renderWithContextTestUtils

A mixin for components that need to know about the active params, query and routes. Any handler on a route with dynamic segments will want to use this.

Instance Methods

getPath()

Returns the current URL path, including query string.

getPathname()

Returns the current URL path without the query string.

getParams()

Returns a hash of the currently active URL params.

getQuery()

Returns a hash of the currently active query params.

isActive(routeName, params, query)

Returns true if a route, params, and query are active, false otherwise.

getRoutes()

Returns an array of the currently active routes, in nesting order.

Examples

Usually you'll just want access to params and query:

// route
<Route name="user" path="user/:name" handler={User} />

// handler
var User = React.createClass({
  mixins: [ Router.State ],

  render: function () {
    var name = this.getParams().name;
    return (
      <div>
        <h1>{name}</h1>
      </div>
    );
  }
});

Let's say you are using bootstrap and want to get active on those li tags for the Tabs:

var Link = require('react-router').Link;
var State = require('react-router').State;

var Tab = React.createClass({

  mixins: [ State ],

  render: function () {
    var isActive = this.isActive(this.props.to, this.props.params, this.props.query);
    var className = isActive ? 'active' : '';
    var link = (
      <Link {...this.props} />
    );
    return <li className={className}>{link}</li>;
  }

});

// use it just like <Link/>, and you'll get an anchor wrapped in an `li`
// with an automatic `active` class on both.
<Tab to="foo">Foo</Tab>