Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

87
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 }
              }}
            />
          )
        }
      />
    );
  }
7 months 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>
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos