Bomber Bomber - 2 months ago 21
React JSX Question

Setup two page site using react-router

I'm trying to setup a really simple two page layout.

Here is my main entry page:

ReactDOM.render(
<Router>
<Route path="/" component={HomeTheme} />
<Route path="blog" component={BlogTheme} />
</Router>
,rootElement
);


I would like to render each route with a different layout, as below:

//Main Layout
render() {
return (
<div>
<Header />
<MainNavigation />
<AboutPage />
<SkillsSection />
<ExperienceSection />
<Blog content={this.state.text} />
<Footer />
</div>
);
}


//Blog Layout
render() {
return (
<div>
<BlogHeader />
<MainNavigation />
<Footer />
</div>
);
}


Problem I have is the layout always defaults to the
HomeTheme
, how can i use a different component for each link?

Answer

You need to use {this.props.children} inside your main component to render all routes.

Your Router should be something like this :

<Route path="/" component={App}>
    <IndexRoute component={HomePage}/>
    <Route path="blog" component={Blog}/>
    <Route path="registration" component={Registration} />
</Route>

Inside your App you should have something like this:

class App extends Component {
    render() {
         return {this.props.children};
    }
}

And inside index route, in this case HomePage you should have a nav to navigate between routes.

import { Link } from 'react-router';
class HomePage extends Component {
   render() {
     return (<ul>
                <li><Link to="/">Home</Link></li>
                <li><Link to="blog">Blog</Link></li>
                <li><Link to="registration">Registration</Link></li>
             </ul>)
  }
}

Hope this helps.

Comments