I'm using react-router dom v6 and I have ProtectedRoute like
export const ProtectedRoute = ({
children,
}: {
children: JSX.Element;
}) => {
let location = useLocation();
const auth = useAuth();
if (!auth.isAuthenticated) {
return <Navigate to="/login" state={{ from: location }} />;
}
// if (isAuthenticated && !userHasRequiredRole) {
// return <AccessDenied />;
// }
return children;
};
In my AppRouter
const AppRouter = () => {
let elements = useRoutes([
// These are the same as the props you provide to <Route>
{ path: '/login', element: <LoginPage /> },
{
path: '/',
element: (
// [1]
<ProtectedRoute>
<BasicLayout />
</ProtectedRoute>
),
children: [
{
path: 'sale',
element: (
// [2]
<ProtectedRoute>
<Sale />
</ProtectedRoute>
),
}
]
}
])
return elements
}
- Can I create HOC component so I dont need to write like this over time (.ie WithProtectedRoute) ?
- Do I need to put the component inside ProtectedRoute every time like this since I put in on path: '/'?