Kid
Kid

Reputation: 2215

Why is not my react router v6 code work, the navigate is not loading component

I'm a beginner so please bear with me, I have this Codesandbox where I learn about the latest React Router v6 Preview and im stuck configuring the routes.

I have simply just a button when clicking it should open a new page like:

navigate("/NotFoundView", { replace: true });

and my routs are very simple like:

const routes = [
  {
    path: "/",
    element: <Header />,
    children: [
      { path: "NotFoundView", element: <NotFoundView /> },
      { path: "404", element: <NotFoundView /> },
      { path: "*", element: <NotFoundView /> }
    ]
  }
];

The app starts and show the <Header />, ok but not the NotFoundView when click button, is not rendered?

Any ide?

Upvotes: 0

Views: 733

Answers (1)

lissettdm
lissettdm

Reputation: 13078

You need to add Outlet component inside Header:

return (
    <div>
    <header>
      <NavBar
        navbarState={navbarOpen}
        handleNavbar={handleNavbar}
        toggle={drawerToggleClickHandler}
        visible={visible}
      />
    </header>
    <Articles/>
    <Outlet/> // your are missing this.
    </div>
  );
}

If you want to render NotFoundView outside of Header component you don't need nested routes. This should work:

const routes = [
  { path: "/", element: <Header />},
  { path: "NotFoundView", element: <NotFoundView /> },
  { path: "404", element: <NotFoundView /> },
  { path: "*", element: <NotFoundView /> }
];

Upvotes: 1

Related Questions