I'm following a tutorial that uses React Router 5. It's your typical "if the user is signed in, redirect them to the users only area, otherwise, bring them to the sign-in page" scenario. How would I best translate the below to something usable with React Router ver 6?
I've pasted both the routing.js and app.js files below.
As for how far I've gotten myself, what I've basically understood is Redirect is now Navigate, and I suppose the "render" property below should be replaced with "element". But then I can't go into app.js and replace my elements with either the IsUserRedirect or ProtectedRoute components because Routes only takes other Route components, so I'm confused how I would best get this all translated over to version 6 neatly.
Thanks for reading this!
import { Route, Redirect } from 'react-router-dom';
export function IsUserRedirect({ user, loggedInPath, children, ...rest }) {
return (
<Route
{...rest}
render={() => {
if (!user) {
return children;
}
if (user) {
return (
<Redirect
to={{
pathname: loggedInPath,
}}
/>
);
}
return null;
}}
/>
);
}
export function ProtectedRoute({ user, children, ...rest }) {
return (
<Route
{...rest}
render={({ location }) => {
if (user) {
return children;
}
if (!user) {
return (
<Redirect
to={{
pathname: 'signin',
state: { from: location },
}}
/>
);
}
return null;
}}
/>
);
}
import React from 'react';
import { BrowserRouter as Router, Switch } from 'react-router-dom';
import { Home, Browse, SignIn, SignUp } from './pages';
import * as ROUTES from './constants/routes';
import { IsUserRedirect, ProtectedRoute } from './helpers/routes';
import { useAuthListener } from './hooks';
export function App() {
const { user } = useAuthListener();
return (
<Router>
<Switch>
<IsUserRedirect user={user} loggedInPath={ROUTES.BROWSE} path={ROUTES.SIGN_IN}>
<SignIn />
</IsUserRedirect>
<IsUserRedirect user={user} loggedInPath={ROUTES.BROWSE} path={ROUTES.SIGN_UP}>
<SignUp />
</IsUserRedirect>
<ProtectedRoute user={user} path={ROUTES.BROWSE}>
<Browse />
</ProtectedRoute>
<IsUserRedirect user={user} loggedInPath={ROUTES.BROWSE} path={ROUTES.HOME}>
<Home />
</IsUserRedirect>
</Switch>
</Router>
);
}```