Fatih Can
Fatih Can

Reputation: 489

React Router v6 Nested Routes doesn't work

I want to render subroute with nested routes .

Expected results -> /bilgi/detay

I've tried like this but it doesn't return any page ..

<Routes>
        <Route path="/" exact element={<Home />} />
        <Route path="bilgi"  element={<Information />} >
           <Route path='detay'  element={<Contact/>}/>
        </Route>
</Routes>

Upvotes: 1

Views: 4545

Answers (3)

Nasrin Ariafar
Nasrin Ariafar

Reputation: 1

We cannot render the child route content with children anymore. The New version of react-router-dom uses the Slot/Outlet concept like what vuejs has. We need to indicate that where the parent-provided slot content should be rendered.

Then you need to add in the Information component.

Check the sample here: https://github.com/remix-run/react-router/blob/4d915e3305df5b01f51abdeb1c01bf442453522e/examples/scroll-restoration/src/app.tsx

Upvotes: 0

Drew Reese
Drew Reese

Reputation: 202741

Nested Route components need an Outlet component to be rendered into.

Apply either of the following:

  1. Have Information component render the Outlet for the nested routes to be rendered into. This renders the entirety of Information along with the content of the nested routes.

    import { Outlet } from 'react-router-dom';
    
    ...
    
    const Information = () => {
      ...
    
      return (
        <>
          ... Information JSX ...
          <Outlet /> // <-- nested routes render here
        </>
      );
    };
    

    ...

    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="bilgi" element={<Information />} >
        <Route path="detay" element={<Contact />} />
      </Route>
    </Routes>
    
  2. Convert path="bilgi" into a layout route that renders the Outlet alone and move Information into its own nested index route to be rendered on the matching path of the layout route. Routes render an Outlet by default if no element prop is provided. This renders each routed component individually.

    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="bilgi">
        <Route index element={<Information />} />
        <Route path="detay" element={<Contact />} />
      </Route>
    </Routes>
    

Read more about index routes and layout routes.

You could OFC, not nest the routes at all and render a flat list of routes with absolute paths.

<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/bilgi" element={<Information />} />
  <Route path="/bilgi/detay" element={<Contact />} />
</Routes>

Upvotes: 5

Chinmay Dey
Chinmay Dey

Reputation: 144

You can do like

<Routes>
    <Route path="/" exact element={<Home />} />
    <Route path="/bilgi" exact element={<Information />} />
    <Route path='/bilgi/detay' exact element={<Contact/>}/>
</Routes>

Upvotes: 0

Related Questions