what changes do you need to make to react router 6?

In react-router-dom version 6 gone are custom Route components, replaced by wrapper components that handle the logic of rendering content or the redirect.

An example replacement could be as follows:

const PrivateWrapper = ({ isAuthenticated, children }) => {
  const location = useLocation();
  
  return isAuthenticated ? (
    children
  ) : (
    <Navigate to="/login" state={{ from: location }} />
  );
};

Usage:

<Routes>
  <Route
    path="...."
    element={(
      <PrivateWrapper isAuthenticated={....}>
        <SomeProtectedComponent />
      </PrivateWrapper>
    )}
  />
</Routes>

And to make the PrivateWrapper a little more usable it can render an Outlet instead of a children prop for nested Route components to be rendered into.

const PrivateWrapper = ({ isAuthenticated }) => {
  const location = useLocation();
  
  return isAuthenticated ? (
    <Outlet />
  ) : (
    <Navigate to="/login" state={{ from: location }} />
  );
};

Usage:

<Routes>
  <Route element={<PrivateWrapper isAuthenticated={...} />} >
    <Route path="...." element={<SomeProtectedComponent />} />
    ..... other protected routes  ......
  </Route>
</Routes>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top