No routes matched location "/login" react router dom v6

Viewed 56660

I am trying to organize the routes in `react-router-dom v6. And here is my flow:

root AppComponent

function AppComponent() {
  return <AppRoute />;
}

AppRoute.js (base routes)

const AppRoute = () => {
  return (
    <>
      <GuestRoute path="/login" component={Login} />
    </>
  );
};

GuestRoute

const GuestRoute = ({ component: Component, ...rest }) => {
  return (
    <GuestLayout>
      <Routes>
        <Route {...rest} element={<Component />} />
      </Routes>
    </GuestLayout>
  );
};

GuestLayout

const GuestLayout = ({ children, ...rest }) => {
  return (
        <div>
          {children}
        </div>
  );
};

But, when I go to /login, it is not breaking the page, but it is still showing a warning of No routes matched location "/login". I am using react-router-dom v6

2 Answers

If you are trying to share multiple layouts then RRDv6 handles this nicely out-of-the-box.

Layout Routes

Example refactoring to use GuestLayout container:

<Routes>
  <Route path="/" element={<GuestLayout />}>   // <-- layout wraps children routes
    <Route path="login" element={<Login />} /> // <-- "/login"

    // Optional index route if no nested routes match
    <Route
      index                                    // <-- "/"
      element={<div>Default Page Content</div>}
    />
  </Route>
</Routes>

This works by having the parent layout container component rendering an Outlet for its nested routes to be rendered.

const GuestLayout = () => {
  return (
    <div /* your crazy layout styling */ >
      <h1>This is the Guest Layout Page</h1>
      <Outlet /> // <-- matched nested route rendered here
    </div>
  );
};

Edit no-routes-matched-location-login-react-router-dom-v6 (forked)

Not directly a solution but a small typo caused by headaches. Basically, check your route separator character "/". I had accidentally put "" which is obviously incorrect.

Another good way to debug issues is not use all paths "*" as the last route in Routes.

<BrowserRouter>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="*" element={<p>Path not resolved</p>} />
  </Routes>
</BrowserRouter>
Related