Daniel Jenner Daniel Jenner - 1 month ago 24
React JSX Question

React router configuration for an SPA with fixed layout

This is my first post here, hope I'm covering everything and did a search for various topics, watched some vids, read the react router docs before getting stuck. :-(

I'm working on a single page app, which has the following components:


  • Layout - parent component, has two children:


    • Maps - child component

    • Events - child component, has one child component:


      • EventDetails





Trying to configure react router to keep the Layout component on the page at all times, and render Maps and Events. Inside Events, when clicking on a link with an event_id (got the link working), it should display into EventDetails. I can't figure out how to get the EventDetails component to display into Events, with the Layout still displaying.

I'm pretty sure I've got my routes mis-configured, or don't really understand IndexRoute completely....thanks in advance for looking.

An image and some code below of my router config.

An imgur link of a layout diagram: http://i.imgur.com/lOtpWqE.png

And a link to the

React router config:

<Router history={hashHistory}>

<Route path="/" component={Layout} >
<Route path="/events/:event_id" component={EventDetail} />
</Route>



Answer

React-router controls what should be visible by injecting component into children prop.

Let's imagine you have the following routes:

<Route path="/" component={Layout} >
    <Route path="/maps" component={Maps} />
    <Route path="/events/" component={Events}>
       <Route path="/events/:event_id" component={EventDetail}>
    </Route>
</Route>

With these routes react-router will automatically pass the Maps component as children prop in the Layout component when you are on /maps path or the Event component when you are on /event. The same thing happens for nested components/routes. Your job is to use {this.props.children} in render method of Root component and children components which want to display other nested components.

To sum up your Layout component render method should look like this:

render() {
   <div>
      <div> [LAYOUT] This part doesn't change between routes </div>
      <div>
          {this.props.children} // here I render nested component like events or maps
      </div>
   </div>
}

Then your Event component

 render() {
       <div>
          <div> [EVENT] This part doesn't change between nested event routes </div>
          <div>
              {this.props.children} // here I render nested component inside event route like EventDetails
          </div>
       </div>
    }

Here you have collection of lessons for react-router: https://github.com/reactjs/react-router-tutorial/tree/master/lessons (Lesson 7 is your case).

IndexRoute is a Route component with path="/"