React Router: router.ts:11 No routes matched location "/manage"

Viewed 253

I am using react-router and write the code like below.

I think all code is written well.

And when I go to '/manage', Manage.js file is properly open.

However I keep facing warning message:

React Router: router.ts:11 No routes matched location "/manage"

What is the problem?

<ApolloProvider client={client}>
  <BrowserRouter>
    {isLoggedIn ? (
      <Routes>
        <Route path="/statistics" element={<Statistics />} />
        <Route path="/manage" element={<Manage />} />
        <Route path="/info" element={<Info />} />
        <Route path="/rank" element={<Rank />} />
        <Route path="/notice" element={<Notice />} />
      </Routes>
    ) : (
      <Routes>
        <Route exact path="/" element={<Home />} />
      </Routes>
    )}
  </BrowserRouter>
</ApolloProvider>
1 Answers

I'm certain you are seeing this warning/error because at certain times there isn't any route rendering on path "/manage".

One way to resolve is to implement route protection and unconditionally render the routes.

Example:

Create a protected layout route to conditionally render a redirect to the "/" path for unauthenticated users, otherwise render an Outlet for the protected component.

import { Navigate, Outlet } from 'react-router-dom';

const ProtectedRoute = ({ isLoggedIn }) => {
  return isLoggedIn
    ? <Outlet />
    : <Navigate to="/" replace />;
};

export default ProtectedRoute;

Create an anonymous layout route that does the inverse of the protected layout route component and redirects to one of the protected routes.

import { Navigate, Outlet } from 'react-router-dom';

const AnonymousRoute = ({ isLoggedIn }) => {
  return isLoggedIn
    ? <Navigate to="//statistics" replace />
    : <Outlet />;
};

export default AnonymousRoute;

...

import AnonymousRoute from '../path/to/AnonymousRoute';
import ProtectedRoute from '../path/to/ProtectedRoute';

...

<ApolloProvider client={client}>
  <BrowserRouter>
    <Routes>
      <Route element={<ProtectedRoute isLoggedIn={isLoggedIn} />}>
        <Route path="/statistics" element={<Statistics />} />
        <Route path="/manage" element={<Manage />} />
        <Route path="/info" element={<Info />} />
        <Route path="/rank" element={<Rank />} />
        <Route path="/notice" element={<Notice />} />
      </Route>
      <Route element={<AnonymousRoute isLoggedIn={isLoggedIn} />}>
        <Route path="/" element={<Home />} />
      </Route>
    </Routes>
  </BrowserRouter>
</ApolloProvider>

This is so all routes are rendered at all times and potentially matchable.

Related