Why can I not nest Route components in react-router 4.x?
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