Why can I not nest Route components in react-router 4.x?

scniro picture scniro · Mar 16, 2017 · Viewed 9.9k times · Source

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?

Answer

Tyler McGinnis picture Tyler McGinnis · Mar 17, 2017

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