1.9 KiB
1.9 KiB
Routes Folder
This folder contains the route definitions and components used to manage routing in the React application. It includes public and private routes, as well as nested layouts.
File Structure
routes/
├── PrivateRoute.jsx
├── AppRoutes.jsx
└── index.js
PrivateRoute.jsx
PrivateRoute is a wrapper component that restricts access to certain routes based on the user's authentication status. Only logged-in users can access routes wrapped inside PrivateRoute.
Example Usage
import { Navigate, Outlet } from "react-router-dom";
import { useAuth } from "../auth"; // custom hook to get auth status
const PrivateRoute = () => {
const { isLoggedIn } = useAuth();
return isLoggedIn ? <Outlet /> : <Navigate to="/login" />;
};
export default PrivateRoute;
<Outlet /> allows nested routes to be rendered inside the PrivateRoute.
AppRoutes.jsx
This file contains all the route definitions example of the app. It can use layouts from the layouts folder to wrap sections of the app.
Example Usage
import { Routes, Route } from "react-router-dom";
import PrivateRoute from "./PrivateRoute";
// Layouts
import MainLayout from "../layouts/MainLayout";
import AuthLayout from "../layouts/AuthLayout";
// Pages
import Dashboard from "../pages/Dashboard";
import Profile from "../pages/Profile";
import Login from "../pages/Login";
const AppRoutes = () => {
return (
<Routes>
{/* Public Routes */}
<Route element={<AuthLayout />}>
<Route path="/login" element={<Login />} />
</Route>
{/* Private Routes */}
<Route element={<PrivateRoute />}>
<Route element={<MainLayout />}>
<Route path="/" element={<Dashboard />} />
<Route path="/profile" element={<Profile />} />
</Route>
</Route>
</Routes>
);
};
export default AppRoutes;