Search code examples
reactjsreact-router-dom

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


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


Solution

  • If you are trying to share multiple layouts then react-router-dom@6 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)