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 }
}}
/>
)
}
/>
);
}
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>