Anto Anto - 2 months ago 7
React JSX Question

IndexRoute not being displayed inside a route

I am a React novice and I have created a basic routing app that contains a route and an index route as a child. The routes.js file is the following:

var React = require('react');
var ReactRouter = require('react-router');
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;
var browserHistory = ReactRouter.browserHistory;
var IndexRoute = ReactRouter.IndexRoute;
var ApplicationHeader = require('../new_components/ApplicationHeader');
var MainPage = require('../new_components/MainPage');

var routes = (
<Router history={browserHistory}>
<Route path="/" component={ApplicationHeader}>
<IndexRoute component={MainPage}/>
</Route>
</Router>
);

module.exports = routes;


The ApplicationHeader.js file is the following:

var React = require('react');

var ApplicationHeader = React.createClass({

render: function () {
return (<header>
<div>Application Header</div>
</header>)
}
}
)

module.exports = ApplicationHeader;


The MainPage.js file is the following:

var React = require('react');

var MainPage = React.createClass({

render: function(){
return(<div>Main Page</div>);
}
})

module.exports = MainPage;


When running the application however, only the 'Application Header' element is shown. I do expect that the main page element should be shown too, but it doesn't. Does anyone know what am I doing wrong?

Answer

In your ApplicationHeader component you need to render the children as well

var React = require('react');

var ApplicationHeader = React.createClass({

    render: function () {
      return (
        <div>
           <header>
             <div>Application Header</div>
           </header>
           <div>{this.props.children}</div> 
        </div>
      )
    }
  }
)

module.exports = ApplicationHeader;