Getting Started with React Router

Setting up the Routing Structure


React router uses components to map URLs to views. To use react-router, import "Router", "Route", "IndexRoute", and "hashHistory" from react-router, and declare the routing hierarchy in the ReactDOM.render() call. The "Router" component instantiates the router, and then "Route" creates a route for URLs that says URLs that start with "/" render the "App" component. Routes can be nested, so let's create two nested routes.

The first route is an "IndexRoute" that displays the "Home" component. This means that going to 'localhost:4000' will display the 'App' component with the 'Home' component underneath. The second component will be the 'Login' component, which will display the login form, so when you navigate to '/login', you'll see the 'App' component with the 'Login' component underneath.

Set up routes
import { Provider } from 'react-redux';
import ReactDOM from 'react-dom';
import React from 'react';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';

import App from './components/App';
import Home from './components/Home';
import Login from './components/Login';
import store from './store';

  <Provider store={store}>
    <Router history={hashHistory}>
      <Route path="/" component={App}>
        <IndexRoute component={Home} />
        <Route path="login" component={Login} />
), document.getElementById('main'));

Now that your routing structure says which component should be rendered within the 'App' component, the 'App' component can no longer hard-code the 'Home' component, so let's get rid of it. The component to be rendered is represented by the props.children property if you add this magic App.contextTypes snippet, which tells react-router to attach the children property to this component's props.

Render routed child components within the App component
import Header from './Header';
import Home from './Home';
import React from 'react';
import { connect } from 'react-redux';

const mapStateToProps = state => ({
  appName: state.appName

class App extends React.Component {
  render() {
    return (
        <Header appName={this.props.appName} />

App.contextTypes = {
  router: React.PropTypes.object.isRequired

export default connect(mapStateToProps, () => ({}))(App);

I finished! On to the next chapter