Home > database >  is it ok to use React Router "Nested" routes
is it ok to use React Router "Nested" routes

Time:08-11

i have a React app that uses React Router v5 (although i think the question applies to v4,5, and 6).

Here is what I want to do: in App.js:

<Router>
   <Route path='/main' component={Main}/>
   <Route path='/admin' component={Admin}/>
</Router>

And then in Main.js I have 2 other routes:

const Main=()=> {
    
   return (
      <div className='some-special-styling-only-for-main'>
          <Route path='/dashboard' component={Dashboard}/>
          <Route path='/calculator' component={Calculator}/>
      </div>

   )
}

This works, but is there anything wrong with it and is it best practice? I am asking because I notice some other Routers like react-location do not allow this (you have to define all routes in one place). Also I've never seen anyone else do it after hours of researching online.

CodePudding user response:

These are descendent routes, not nested routes, but that doesn't matter as the question, as posed, is a bit subjective. react-router-dom allows it, so yes, it's ok to do. There is no issue with React components rendering descendent routes.

This is a very common routing pattern in RRDv4/5. RRDv6 allows it and made nesting routes even easier than in previous versions.

I'm not sure where exactly you were looking for examples of rendering descendent/"nested" routes and not finding any, but there's an official Nesting Example in the v5 docs.

  • Related