Mohammed
Mohammed

Reputation: 56

React Router V6 Not rendering pages

I am trying to get my routes working from my nav bar but no pages get rendered. My follow is as follows:

App.tsx:

  <div>
    <Routes>
      <Route path={login} element={<LoginPage />} />
    </Routes>
    <Routes>
      <Route path='/' element={<Dashboard />}/>
    </Routes>
  </div>

Dashboard.tsx:

export default function Dashboard() {

  const mainPanel = React.createRef();


  const getRoutes = (routes: any) => {
    return routes.map((prop: any, key: number) => {
      if (prop.collapse) {
        return getRoutes(prop.views);
      }

      if (prop.layout) {
        console.log(prop.component)
        console.log(key)
        return (
          <Route
            path={prop.layout + prop.path}
            element={prop.component}
            key={key}
          />
        );
      } else {
        return null;
      }
    });
  };


  return (
    <div className="wrapper">
      <Sidebar activeColor={"danger"} protectedRoutes={ProtectedRoutes} LoggedInUser='Test' AccountRoutes={AccountRoute} />
      <div className="main-panel" ref={mainPanel as React.RefObject<HTMLDivElement>}>
        <TopNavbar />
        <Routes>
          {getRoutes(ProtectedRoutes)}
        </Routes>
      </div>
      <Outlet />
    </div>
  );
}

and my Routes.ts:

export const ProtectedRoutes : ProtectedRoute[] = [
    {
        path: "dashboard",
        name: "Dashboard",
        icon: "nc-icon nc-paper",
        component: DashboardPage,
        layout: "/",
    },
]

The follow was working but for some reason I am getting redirected to a blank page and in my console it says "No Routes Matched Location /dashboard"

Even without the Nav Bar if I go to the URL directly, it still does not work.

Upvotes: 2

Views: 2111

Answers (1)

Drew Reese
Drew Reese

Reputation: 203408

In react-router-dom v6 all paths are always exactly matched. A trailing "*" wildcard character is used to allow path matching of nested routes. <Route path='/' element={<Dashboard />}/> should be <Route path='/*' element={<Dashboard />}/> if you want it to match and render nested route components. Same for any nested routes that render yet more nested routes.

Example:

<div>
  <Routes>
    <Route path={login} element={<LoginPage />} />
    <Route path='/*' element={<Dashboard />}/>
  </Routes>
</div>

Upvotes: 1

Related Questions