14

From React Router's docs:

All children of a <Switch> should be <Route> or <Redirect> elements. Only the first child to match the current location will be rendered.

Nonetheless, nested <Switch> statements are allowed. I use the pattern to break up large numbers of <Routes>:

<Switch>
  <Route path="/foo" component={FooRouter} />
  <Route path="/bar" component={BarRouter} />
  <Route path="/baz" component={BazRouter} />
</Switch>

...

const FooRouter = () => (
  <Switch>
    <Route exact path="/foo/:id" component={ViewFoo} />
    <Route exact path="/foo/new" component={NewFoo} />
  </Switch>
)

const BarRouter = () => (
  <Switch>
    <Route exact path="/bar/new" component={NewBar} />
  </Switch>
)

....

Curious if there is a better method for breaking up large numbers of routes and if nested <Switch> statements should be avoided?

cheshireoctopus
  • 1,538
  • 1
  • 20
  • 27
  • 2
    The quote you started your question with resolved my issue. After joy of React useful suggestions and warnings it's a pain to have something broken when using other libraries just because you don't remember the docs by heart. – Mikhail Vasin Jul 10 '18 at 13:18

1 Answers1

2

as you solve it just fine when you have a lot of nested route yo can speared them across the app and make a dynamic routes but soon react-router-dom v6 will be release with a huge upgrade one of them is useRoutes that let you configure your routes like this:

let element = useRoutes([
    // A route object has the same properties as a <Route>
    // element. The `children` is just an array of child routes.
    { path: '/', element: <Home /> },
    {
      path: 'users',
      element: <Users />,
      children: [
        { path: '/', element: <UsersIndex /> },
        { path: ':id', element: <UserProfile /> },
        { path: 'me', element: <OwnUserProfile /> },
      ]
    }
  ]);

introduction to react-router-dom v6 they have some cool new feature that worth to watch for one of them is the replace of with witch help you a lot with nested routes and fun thing you don't gonna need to use the exact anymore

     <Routes>
        <Route path="/" element={<UsersIndex />} />
        <Route path=":id" element={<UserProfile />} />
        <Route path="me" element={<OwnUserProfile />} />
      </Routes>

this is how it gonna look with the new feature

TalOrlanczyk
  • 786
  • 3
  • 14