Home > Net >  Nested routes won't work using React Router 6
Nested routes won't work using React Router 6

Time:03-08

When I click Add card button (IconButton component) I should be able to navigate to the Add card page but it doesn't work.

This is my code:

App.js:

<Routes>
  <Route index element={<Home />} />
  <Route path="login" element={<Login />} />
  <Route path="signup" element={<Signup />} />
  <Route path="manage-cards" element={<ManageCards />}>
    <Route path="add-card" element={<h1>Hello world</h1>} />
  </Route>
  <Route path="manage-code" element={<ManageCode />} />
</Routes>

ManageCards.jsx:

import React from "react";
import { Link } from "react-router-dom";

import IconButton from "../../components/iconButton/IconButton";

import addCardIcon from "../../assets/img/Add card.png";

const ManageCards = () => {
  return (
    <div className="manage-cards">
      <div className="manage-cards__buttons">
        <Link to="add-card">
          <IconButton
            icon={addCardIcon}
            altText="Add card"
            iconText="Add card"
          />
        </Link>
      </div>
    </div>
  );
};

export default ManageCards;

CodePudding user response:

An <Outlet> should be used in parent route elements to render their child route elements. This allows nested UI to show up when child routes are rendered. If the parent route matched exactly, it will render a child index route or nothing if there is no index route.

Did you add Outlet ?

CodePudding user response:

Use it

import React from "react";
import { Link,Outlet  } from "react-router-dom";

import IconButton from "../../components/iconButton/IconButton";

import addCardIcon from "../../assets/img/Add card.png";

const ManageCards = () => {
  return (
    <div className="manage-cards">
      <div className="manage-cards__buttons">
        <Link to="add-card">
          <IconButton
            icon={addCardIcon}
            altText="Add card"
            iconText="Add card"
          />
        </Link>
      </div>

     <Outlet />
    </div>
  );
};

export default ManageCards;

CodePudding user response:

I wanted to render the add-card in a different page, the problem with Outlet will cause it to render in the same page. So that's how I managed to fix the issue:

<Routes>
  <Route index element={<Home />} />
  <Route path="login" element={<Login />} />
  <Route path="signup" element={<Signup />} />
  <Route path="manage-cards">
    <Route index element={<ManageCards />} />
    <Route path="add-card" element={<h1>Hello world</h1>} />
  </Route>
  <Route path="manage-code" element={<ManageCode />} />
</Routes>

  • Related