Notes

React Router Basics

Edit on GitHub

ReactJS
2 minutes
1ReactDOM.render((
2  <Router history={browserHistory}>
3    <Route path='/' component={Users} />
4    <Route path='/other' component={Other} />
5  </Router>
6), document.getElementById('root'))

history is required.

What we did above is we mounted a Router to the DOM, it is now going to take Routes. A route takes a path (URL) and shows a component on that path.

If you want to navigate anywhere within the site, you use Link. You’ll only use actual href when you want to move away from the site. A link looks like this:

1<Link to='/other'>Other</Link>

You will not be making any server requests to go to any of these different links/pages.

Nested Routes

You can have nested routes just like you can have nested components

1ReactDOM.render((
2  <Router history={browserHistory}>
3      <Route path='/' component={Main}>
4        <Route path='/users' component={Users} />
5        <Route path='/other' component={Other} />
6      </Route>
7  </Router>
8), document.getElementById('root'))

What the could above will do is that it’ll load the Users route/component inside the Main route/component.

IndexRoute

IndexRoute let’s you render props.children. It’s aimed at setting a default UI that opens when you are at the route.

1ReactDOM.render((
2  <Router history={browserHistory}>
3    <Route path='/' component={AppLayout}>
4      <IndexRoute component={Users} />
5      <Route path='/other' component={Other} />
6    </Route>
7  </Router>
8), document.getElementById('root'))

Props

You can also pass props, like so:

1ReactDOM.render((
2  <Router history={browserHistory}>
3    <Route path='/' component={AppLayout}>
4      <IndexRoute component={Users} />
5      <Route path='/profile/:id' component={UserProfile}} />
6    </Route>
7  </Router>
8), document.getElementById('root'))