• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

200
Vistas
I upgraded to React-router 6 and my code is broken, what changes would i have to make?

I am trying to port this over to v6, however, it appears that I have not gotten the syntax correctly. this code works perfectly when using react-router v5.

I know for instance that the routing syntax changes.

Urls.js

import React from "react";
import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";

import Login from "./components/Login";
import Home from "./components/Home";

// A wrapper for <Route> that redirects to the login screen if you're not yet authenticated.

function PrivateRoute({ isAuthenticated, children, ...rest}) {
    return (
      <Route
        {...rest}
        render={({ location }) =>
        isAuthenticated ? (
            children
          ) : (
            <Redirect
              to={{
                pathname: "/login/",
                state: { from: location }
              }}
            />
          )
        }
      />
    );
  }
about 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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>
about 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda