Skip to content

Router Snippets

Nick S. Plekhanov edited this page Sep 8, 2016 · 1 revision

Router Core

Router: Routes template — rrnr

import React from 'react';
import { Route, IndexRoute, Redirect } from 'react-router';

import App from './App';
import MainView from 'components/MainView';
import NotFoundView from 'components/NotFound';

export default (
  <Route path="/" component={App}>
    <IndexRoute component={MainView} />
    <Route path="404" component={NotFoundView} />
    <Redirect from="*" to="404" />
  </Route>
);

Router: Render a Route — rrrr

import { render } from 'react-dom';
import { Router } from 'react-router';
import { browserHistory } from 'react-router';

import routes from './routes';

render(
  <Router history={browserHistory} routes={routes} />,
  document.getElementById('app')
);

Router: Navigate with Link — rrl

<Link to="/${1:route}">${2:Title}</Link>

Router: Active Link — rral

<Link to="/${1:about}" activeClassName="${2:active}">${3:About}</Link>

Router: Index Link — rril

<IndexLink to="/" activeClassName="${1:active}">${2:Home}</IndexLink>

Router: Index Link with onlyActiveOnIndex property — rrila

<Link to="/" activeClassName="${1:active}" onlyActiveOnIndex={true}>${2:Home}</Link>

Router: Include router context types — rrct

static contextTypes = {
  router: PropTypes.object.isRequired
};

Router: Navigation Link Wrapper — rrnlw

import React, { Component } from 'react';
import { Link } from 'react-router';

export default class NavLink extends Component {
  render() {
    return <Link {...this.props} activeClassName="${1:active}" />;
  }
}

Router: Navigation Link — rrnl

<NavLink to="/${1:route}">${2:Title}</NavLink>

Router: Get URL params — rrup

this.props.params.${1:name}

Router: Navigate programatically — rrpu

this.context.router.push('/${1:route}');

Router Routes

Router Routes: Index route — rrir

<IndexRoute component={${1:Main}} />

Router Routes: Regular route — rrregr

<Route path="${1:name}" component={${2:Component}} />

Router Routes: Redirect — rrred

<Redirect from="${1:/route/:id}" to="${2:/another/:id}" />