Mohammed Modather
Mohammed Modather

Reputation: 1

Nested routes won't work using React Router 6

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;

Upvotes: 0

Views: 499

Answers (3)

Mohammed Modather
Mohammed Modather

Reputation: 1

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>

Upvotes: 0

Vida Hedayati
Vida Hedayati

Reputation: 336

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;

Upvotes: 0

Mile Mijatović
Mile Mijatović

Reputation: 3177

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 ?

Upvotes: 1

Related Questions