Seyed-Amir-Mehrizi
Seyed-Amir-Mehrizi

Reputation: 739

Nested routing in react-router-dom V6

I hope All you are doing well. Recently I have done the project with react and make a sample here. The problem is in routing. I want to display the child route under its parent but unfortunately I did not make it. I would be truly appreciated it, If anyone can explain the issue or fix the code.

App

import "./styles.css";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Login from "./Login";
import Main from "./Main";

export default function App() {
  return (
    <div className="App">
      <Router>
        <Routes>
          <Route path="/" element={<Login />} />
          <Route path="/main" element={<Main />}></Route>
        </Routes>
      </Router>
    </div>
  );
}

Main

import React from "react";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  Outlet,
  Link
} from "react-router-dom";
import Child1 from "./Child1";
import Child2 from "./Child2";

export default function Main() {
  return (
    <div>
      <h1>main page</h1>
      <Link to="/main/child1">child 1</Link>||||
      <Link to="/main/child2">child 2</Link> ||||
      <Link to="/">log out</Link>
      <Outlet />
      <Routes>
        <Route path="/main/child1" element={<Child1 />} />
        <Route path="/main/child1" element={<Child2 />} />
      </Routes>
    </div>
  );
}

child 1 & 2

export default function Child1() {
  return <div>Child1</div>;
}
export default function Child2() {
  return <div>Child2</div>;
}

Bests.

Upvotes: 11

Views: 14961

Answers (1)

Drew Reese
Drew Reese

Reputation: 202605

Issue

The main issue is that your root path matcher is specified in such a way as to not match the nested paths so the Main component is unmounted.

Solution

App

Here the path for Main should specify a wildcard matcher to allow continued matching of sub-routes, path="/main/*".

export default function App() {
  return (
    <div className="App">
      <Router>
        <Routes>
          <Route path="/" element={<Login />} />
          <Route path="/main/*" element={<Main />} /> // <-- allow sub-route matches
        </Routes>
      </Router>
    </div>
  );
}

Main

Note that all the links and paths have also been updated to be relative links/paths versus absolute.

export default function Main() {
  return (
    <div>
      <h1>main page</h1>
      <Link to="child1">child 1</Link> ||||{" "}
      <Link to="child2">child 2</Link> ||||{" "}
      <Link to="/">log out</Link>
      <Outlet />
      <Routes>
        <Route path="child1" element={<Child1 />} />
        <Route path="child2" element={<Child2 />} />
      </Routes>
    </div>
  );
}

Edit nested-routing-in-react-router-dom-v6

Upvotes: 24

Related Questions