How in the world does one use nested routes in react-router, specifically, version 4.x? The following worked well in previous versions...
<Route path='/stuff' component={Stuff}>
<Route path='/stuff/a' component={StuffA} />
</Route>
Upgrading to 4.x throws the following warning...
Warning: You should not use <Route> component and <Route children> in the same route; <Route children> will be ignored
What in the heck is going on here? I've scoured the docs for hours and can not successfully get nested routes working. How does one use <Route>
components to nest their routes in react-router v4? How does my simplistic example translate to v4.x API compliance to nest a route?
With react-router v4 and v5 you can also use the render
prop to nest routes
<Route
path='/stuff'
render={({ match: { url } }) => (
<>
<Route path={`${url}/`} component={Stuff} exact />
<Route path={`${url}/a`} component={StuffA} />
</>
)}
/>
In my opinion this syntax ends up more readable in most situations, compared to splitting out the sub-routes into a separately defined component passed in through the component
prop.
I posted a similar answer here but noticed this question also has a lot of views and so thought it would be helpful to port it here.
Forget what you know about React Router < v4. You nest routes by literally nesting <Routes>
. Check this example. Specifically check out the Topics component. You don't declare your routes up front but instead dynamically when a component renders.
import React from 'react'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
const BasicExample = () => (
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/topics">Topics</Link></li>
</ul>
<hr/>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route path="/topics" component={Topics}/>
</div>
</Router>
)
const Home = () => (
<div>
<h2>Home</h2>
</div>
)
const About = () => (
<div>
<h2>About</h2>
</div>
)
const Topics = ({ match }) => (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/rendering`}>
Rendering with React
</Link>
</li>
<li>
<Link to={`${match.url}/components`}>
Components
</Link>
</li>
<li>
<Link to={`${match.url}/props-v-state`}>
Props v. State
</Link>
</li>
</ul>
{/* NESTED ROUTES */}
<Route path={`${match.url}/:topicId`} component={Topic}/>
<Route exact path={match.url} render={() => (
<h3>Please select a topic.</h3>
)}/>
</div>
)
const Topic = ({ match }) => (
<div>
<h3>{match.params.topicId}</h3>
</div>
)
export default BasicExample
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With