entithat
entithat

Reputation: 333

Router can not find nested Route components v6

I'm using react-router v6 and I have such simple App component.

type RouteType = {
  path: string;
  element: any;
}

function App() {
  const [user] = useAuthState(auth);

  const USER_ROUTES: RouteType[] = user ? [
    { path: '/signin', element: <Login /> },
    { path: '/signup', element: <Signup /> },
  ] : [
    { path: '/games', element: <Games /> },
    { path: '/tournaments', element: <Tournaments /> },
    { path: '/mymatches', element: <MyMatches /> },
  ];

  const PUBLIC_ROUTES: RouteType[] = [
    { path: '*', element: <NotFound /> },
    { path: '/', element: <Home /> },
  ];

  return (
    <>
      <Header />
      <Routes>
        {[...USER_ROUTES, ...PUBLIC_ROUTES].map(
          ({ path, element }, i) => <Route key={i} path={path} element={element} />,
        )}
      </Routes>
    </>
  );
}

But independently on user value it always renders * route (NotFound). How can I rewrite this piece of code with such concept but without error?

Thanks.

Upvotes: 1

Views: 62

Answers (1)

Drew Reese
Drew Reese

Reputation: 202741

From what I can see you've inverted the logic for your user routes. When user is truthy you render the signin/signup routes instead of the routes an "authentictated" user should be able to access.

When user is falsey "/games", "/tournaments", and "/mymatches" is returned for user routes. If you attempt to navigate to "/signin" the "*" path catches it and renders NotFound component since no route for "/signin" is currently rendered.

Swap the routes returned for USER_ROUTES when user is truthy.

function App() {
  const [user] = useAuthState(auth);

  const USER_ROUTES: RouteType[] = user ? [
    // truthy user, render user routes
    { path: '/games', element: <Games /> },
    { path: '/tournaments', element: <Tournaments /> },
    { path: '/mymatches', element: <MyMatches /> },
  ] : [
    // falsey user, render signin/signup routes to authenticate
    { path: '/signin', element: <Login /> },
    { path: '/signup', element: <Signup /> },
  ];

  const PUBLIC_ROUTES: RouteType[] = [
    { path: '*', element: <NotFound /> },
    { path: '/', element: <Home /> },
  ];

  return (
    <>
      <Header />
      <Routes>
        {[...USER_ROUTES, ...PUBLIC_ROUTES].map(({ path, element }) => (
          <Route key={path} path={path} element={element} />
        ))}
      </Routes>
    </>
  );
}

Upvotes: 1

Related Questions