JohnEisenheim
JohnEisenheim

Reputation: 87

How to render a nested component with react-router

This is a noob question. I'm developing a universal react application using react-isomorphic-starterkit boilerplate (https://github.com/RickWong/react-isomorphic-starterkit). I would create a "fixed" sidebar on the left that contains links to the other pages rendered on a child of the main container on the right. Here's my code:

routes.js

module.exports = (
    <Router history={browserHistory}>
        <Route path="/" component={Main}>
            <Route path='/inbox' component={Inbox} />
        </Route>
    </Router>
);

Main.js

export default class Main extends React.Component {
    constructor(props, context){
        super(props,context);
        console.log('Main props', props);
        console.log('Main context', props);
    }
    /**
     * componentWillMount() runs on server and client.
     */
    componentWillMount () {
        if (__SERVER__) {
            console.log("Hello server");
        }

        if (__CLIENT__) {
            console.log("Hello client");
        }
    }

    /**
     * Runs on server and client.
     */
    render () {
        return (
                <App/>
        )
    }
}

App.js

class App extends React.Component{

  constructor(props, context) {
    super(props, context);
    console.log('App props ', props);
  }

  render(){
    return (
      <div>
          <Sidebar/>
          <RightContent />
      </div>
    )
  }

}

RightContent.js

class RightContent extends React.Component{
  render(){
    return (
      <div id="b" style={{backgroundColor:"#EEF0F4", width:"100%"}}>
        <NavBar />
        {this.props.children}
      </div>
    )
  }
}

Problem is: Inbox component (a simple <div>) is not rendering when I click on the sidebar with <Link to="..."> tag. I don't know if the following thing is correct: as you can see, in App.js class constructor prints props variable...but the output is undefined. However, in Main.js props are printed correctly. react-router version is greater than 2. Could anyone help me?

Upvotes: 1

Views: 1841

Answers (1)

BradByte
BradByte

Reputation: 11093

You're not passing props down to App, so unless you use the location context, it won't have them.

You should do...

render () {
  return (
    <App {...this.props}/>
  )
}

Then, you should have access to this.props.children in App to render the nested route(s). You'll need to specify that in RightContent too...

render(){
  return (
    <div>
      <Sidebar/>
      <RightContent>
        {this.props.children}
      </RightContent>
    </div>
  )
}

See the tutorial in the docs... https://github.com/reactjs/react-router/blob/master/docs/Introduction.md#with-react-router

Upvotes: 1

Related Questions