Milos Milos - 5 months ago 18
Javascript Question

React Router, how do I tell the router to render to a component?

I'm currently able to use my navbar (TopPane component) to go from page to page using react router version 3.0.5. What I want to do is have it so that if I click something on the top pane, the route renders to the center component instead of the entire page. Here's how my hierarchy looks like.

App
--Left Pane
--Top Pane
--Center Pane

My routes.js is this:



import React from 'react';
import { Router, Route, browserHistory } from 'react-router';

import App from './components/App.jsx';
import Models from './components/Models.jsx';
import Projects from './components/Projects.jsx';
import Contact from './components/Contact.jsx';
import About from './components/About.jsx';
import CenterPane from './components/CenterPane.jsx';

export default (
<Router history = {browserHistory}>
<Route path="/" component={App} />
<Route path="/models" component={Models} />
<Route path="/projects" component={Projects} />
<Route path="/contact" component={Contact} />
<Route path="/about" component={About} />
</Router>
);





My App.jsx is this:



import React from 'react';
import LeftPane from './LeftPane.jsx';
import RightPane from './RightPane.jsx';
import CenterPane from './CenterPane.jsx';
import TopPane from './TopPane.jsx';
import Models from './Models.jsx';
import Projects from './Projects.jsx';
import Contact from './Contact.jsx';
import Router from 'react-router';

class App extends React.Component {
constructor() {
super();
this.state = { none: 'none' };
}

render() {
return (
<div>
<div className="container-fluid">
<div>
<TopPane />
</div>
<div className="container-fluid text-center">
<div className="row content">
<div className="col-sm-2 sidenav">
<LeftPane />
</div>
<div className="col-sm-10 text-left">
<CenterPane />
</div>
</div>
</div>
</div>
</div>
);
}
}

export default App;





Can anyone let me know how to go about getting react-router to render the routes only on the CenterPane component instead of the entire page disappearing (and thus I lose my top pane navbar because it's only on App.jsx).

Answer Source

For that you need to change the route structure, you need to create nested routes and make App as parent of all, by this way when you click in top panel only a part of App component will change not the entire page.

Define the routes like this:

export default (
  <Router history = {browserHistory}>
      <Route path="/" component={App}>
         <Route path="/models" component={Models} />
         <Route path="/projects" component={Projects} />
         <Route path="/contact" component={Contact} />
         <Route path="/about" component={About} />
      </Route>
  </Router>
);

Inside App component use this.props.children inside render method, at this place the child route component will get rendered.

For more detail on react-router v3 check the DOC.