Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
112
rated 0 times [  115] [ 3]  / answers: 1 / hits: 72219  / 7 Years ago, thu, march 23, 2017, 12:00:00

I need multiple nested routes in react-router-dom



I am using v4 of react-router-dom



I've got my



import { BrowserRouter as Router, Route } from 'react-router-dom';


and I need the components to render like so



--- Login
--- Home
--- Page 1
--- Page 2
--- Page 3
--- About
--- etc


The Home component contains a Header component that is common to Page1, Page2, and, Page3 components, but is not present in Login and About.



My js code reads like so



<Router>
<div>
<Route path='/login' component={Login} />
<Home>
<Route path='/page1' component={Page1} />
<Route path='/page2' component={Page2} />
<Route path='/page3' component={Page3} />
</Home>
<Route path='/about' component={About} />
</div>
</Router>


I expect the Login component to show only on /login
When I request for /page1, /page2, /page3, they should contain the Home component and that page's content respectively.



What I get instead is the Login component rendered and below that Page1's component is rendered.



I'm pretty sure that I'm missing something very trivial or making a really silly mistake somewhere, and would appreciate all the help I could get. I've been stuck with this for the last two days.


More From » reactjs

 Answers
60

Use Switch component in router v4



<Router>
<Switch>
<Route path='/login' component={Login} />
<Route path='/about' component={About} />
<Home>
<Route component={({ match }) =>
<div>
<Route path='/page1' component={Page1} />
<Route path='/page2' component={Page2} />
<Route path='/page3' component={Page3} />
</div>
}/>
</Home>
</Switch>




export default class Home extends Component {
render() {
return (
<div className=Home>
{ this.props.children }
</div>
)
}
}


I think this code shows the basic idea of using component.


[#58416] Wednesday, March 22, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
eddiejoshb

Total Points: 659
Total Questions: 105
Total Answers: 100

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
;