Estoy usando React Router v6 y estoy creando rutas privadas para mi aplicación.
En el archivo Route.js, tengo el código
export default function RouteWrapper({ element: Element, isPrivate, ...rest }) { const { signed, loading } = useContext(AuthContext); if (loading) { return <div></div>; } if (!signed && isPrivate) { return <Navigate to="/" />; } if (signed && !isPrivate) { return <Navigate to="/dashboard" />; } return <Route {...rest} render={(props) => <Element {...props} />} />; }Y en el archivo index.js he escrito como:
return ( <Routes> <Route path="/" element={SignIn} /> <Route path="/register" element={SignUp} /> <Route path="/dashboard" element={Dashboard} isPrivate /> <Route path="/profile" element={Profile} isPrivate /> <Route path="/customers" element={Customers} isPrivate /> <Route path="/new" element={New} isPrivate /> <Route path="/new/:id" element={New} isPrivate /> </Routes> ); }¿Se me escapa algo?
deberías convertir
<Routes> <Route exact path="/" element={Dashboard} /> </Routes>a
<Routes> <Route exact path="/" element={<Dashboard/>} /> </Routes>Además, si desea mantener su interfaz de usuario sincronizada con la URL, utilícela de esta manera.
<BrowserRouter> <Routes> <Route exact path="/" element={<Dashboard/>} /> </Routes> </BrowserRouter>Mejor.
RouteWrapper no es un componente de Route y falla una verificación invariable de react-router-dom .RouteWrapper está representando directamente un componente de Route , que si el primer invariante no falla, desencadenaría otra violación de invariante. Los componentes Route solo pueden ser representados directamente por el componente Routes u otro componente de Route en el caso de crear enrutamiento anidado. En resumen, en react-router-dom@6 los componentes de ruta personalizados ya no son compatibles. En su lugar, debe usar componentes de contenedor/rutas de diseño para manejar este caso de uso.
Convierta RouteWrapper en un componente contenedor que represente un componente Outlet para que se representen los componentes enrutados anidados.
Ejemplo:
import { Navigate, Outlet } from 'react-router-dom'; export default function RouteWrapper({ isPrivate }) { const { signed, loading } = useContext(AuthContext); if (loading) { return <div></div>; } if (!signed && isPrivate) { return <Navigate to="/" />; } if (signed && !isPrivate) { return <Navigate to="/dashboard" />; } return <Outlet />; // <-- nested routes render here } Envuelva las rutas que desea proteger con RouteWrapper .
return ( <Routes> <Route element={<RouteWrapper />}> <Route path="/" element={<SignIn />} /> <Route path="/register" element={<SignUp />} /> </Route> <Route element={<RouteWrapper isPrivate />}> <Route path="/dashboard" element={<Dashboard />} /> <Route path="/profile" element={<Profile />} /> <Route path="/customers" element={<Customers />} /> <Route path="/new" element={<New />} /> <Route path="/new/:id" element={<New />} /> </Route> </Routes> );Consulte Diseño de rutas para obtener más detalles.