Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router 6 alpha 4 nested routes

Giving the following sandbox, not sure to understand how to render the Bb component

import React from "react";
import "./styles.css";
import { Routes, Route } from "react-router";
import { BrowserRouter } from "react-router-dom";

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="a" element={<Aa />}>
          <Route path="b" element={<Bb />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

function Aa() {
  return (
    <p>
      Hello
    </p>
  );
}

function Bb() {
  return <p>World</p>;
}

https://codesandbox.io/s/still-shadow-337zc?file=/src/App.js

browsing to /a/b only renders Aa component

like image 435
AdMer Avatar asked Jan 26 '23 01:01

AdMer


1 Answers

react-router v6 exposes an Outlet element that you must use inside your parent Route so that any nested children can be rendered by react-router-dom isnide of it

import React from "react";
import "./styles.css";
import { Routes, Route } from "react-router";
import { BrowserRouter, Outlet } from "react-router-dom";

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="a" element={<Aa />}>
          <Route path="b" element={<Bb />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

function Aa() {
  return <p>Hello <Outlet /></p>;
}

function Bb() {
  return <p>World</p>;
}

Working demo

If you want only Bb to render at a/b you define it as a separate route like

<BrowserRouter>
  <Routes>
    <Route path="a" element={<Aa />}/>
    <Route path="a/b" element={<Bb />} />
  </Routes>
</BrowserRouter>

You can read more about Route structuring in depth here

like image 153
Shubham Khatri Avatar answered Feb 10 '23 23:02

Shubham Khatri