0

I want to migrate from React Router V5 to V6, I used to map trough private routes and have a HOC that renders each private page components. I'm not sure how do it in same type of fashion for V6.

Here's how my Root component looked like:

const WrappedComponent = () => (
  <Switch>
    <Route exact path="/">
      <Redirect to={routes.LOGIN} />
    </Route>
    <Route exact path={routes.LOGIN} component={Login} />
    {privateRoutes.map((route) => (
      <PrivateRoute
        exact
        component={route.component}
        path={route.path}
        key={route.path}
      />
    ))}
  </Switch>
);

And here's how my PrivateRoute component looks like:

const PrivateRoute = ({ component: Component, ...props }) => {
  const { loggedIn } = useSelector(({ auth }) => auth);

  return (
    <Route
      render={(routerProps) =>
        loggedIn ? (
          <Component {...props} {...routerProps} />
        ) : (
          <Redirect to={{ pathname: routes.LOGIN }} push />
        )
      }
    />
  );
};

What is the way to map trough private routes and render them in React Router V6?

Valerxx22
  • 774
  • 1
  • 11
  • 32

1 Answers1

1

In react-router-dom v6 have Navigate (replacement of Redirect) and Outlet components. I would do

// PrivateRoute.tsx
import { Navigate, Outlet, useLocation } from 'react-router-dom';

import { useAuth } from '../hooks/useAuth';

export const PrivateRoute = () => {
  const location = useLocation();
  const auth = useAuth();
  return auth.isAuthenticated ? (
    <Outlet />
  ) : (
    <Navigate to="/login" state={{ from: location }} replace />
  );
};

and

// AppRouter.tsx
import { useRoutes } from 'react-router-dom';

import { PrivateRoute } from './PrivateRoute';

const AppRouter = () => {
  const elements = useRoutes([
    { path: '/login', element: <LoginPage /> },
    { path: '/', element: <HomePage /> },
    {
      element: <PrivateRoute />,
      children: [
        {
          path: '/',
          element: <BasicLayout />,
          children: [
            {
              path: 'sale',
              // element: <SalePage />,
            },
          ],
        },
      ],
    },
    // Not found routes work as you'd expect
    { path: '*', element: <NotFoundPage /> },
  ]);

  return elements;
};

export default AppRouter;
nart
  • 1,508
  • 2
  • 11
  • 24
  • what about if `sale` path have an optional param `/sale/:id?`, how do you handle that in `useRoutes()` hook – Valerxx22 Oct 12 '22 at 08:11