Protected Route
ProtectedRoute Component
The ProtectedRoute
component is a wrapper component designed for authenticated routes. It ensures that only logged-in users can access certain routes within the application.
Usage
To use the ProtectedRoute
component, simply wrap the routes that require authentication within it. Here's an example of how you can integrate it into your routing setup:
import { memo } from "react";
import { Navigate, Route, Routes } from "react-router-dom";
import { ProtectedRoute } from "../layout/ProtectedRoute";
import { Login } from "../views/auth/Login";
import { OAuthCallback } from "../views/auth/OAuthCallback";
import { Home } from "../views/home/Home";
import ProjectList from "../views/project/ProjectList";
export const AppRoutes = memo(() => (
<Routes>
<Route path="/" element={<Navigate to="/auth/login" />} />
<Route path="/auth/login" element={<Login />} />
<Route path="/oauth/callback" element={<OAuthCallback />} />
<Route element={<ProtectedRoute />}>
<Route path="/home" element={<Home />} />
<Route path="/project" element={<ProjectList />} />
</Route>
</Routes>
));
Props
The ProtectedRoute
component accepts the following props:
children
: ReactNode - The content to be rendered within the protected route.
Behavior
- If user is authenticated, the
ProtectedRoute
component renders its children normally. - If user is not authenticated, the component redirects to login page specified by
to
prop ofNavigate
component.
Notes
- Ensure that the
ProtectedRoute
component is placed appropriately within your route hierarchy to protect the desired routes. - Customize the redirect behavior by adjusting the
to
prop of theNavigate
component within theProtectedRoute
component. - Make sure to handle cases where the user's authentication status changes dynamically within the application.