React is a Javascript library used to build modern fast and scalable User Interfaces(UI).
Layouts are reusable components which defines the structure of application's UI(User Interface) within which main content gets rendered or loaded.
![]() |
| Admin/Dashboard Layout |
In above image the Dashboard or the Admin's layout can be seen where there is a Sidebar and the corresponding main content can be seen on the right side.
Below code defines the private routes(routes which are not public and which requires privileges like access token) which consists of Layout and corresponding pages.
<Route element={<PrivateRoutes />}>
<Route path="/admin" element={<DashboardLayout />}>
<Route path="dashboard" element={<Dashboard />} />
<Route path="categories" element={<Categories />} />
<Route path="products" element={<Products />} />
</Route>
</Route>
Let us see how layouts are managed in React with industry standard code. In below code the <Outlet /> component renders the main or variable content while the Sidebar remains consistent with little changes like active link style and this overall structure/ concept defines the Layout of any application.
import React from 'react'
import "./DashboardLayout.css"
import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom';
function DashboardLayout() {
const navigate = useNavigate();
const location = useLocation();
const handleLogout = () => {
localStorage.removeItem("token");
navigate("/login");
}
const isActive = (path) => {
return location.pathname.includes(path);
};
return (
<div className="container-fluid p-0">
<div className="row g-0">
<nav className="col-md-3 col-lg-2 bg-dark sidebar">
<div className="position-sticky pt-3">
<h5 className="text-white px-3 mb-4">Admin Panel</h5>
<ul className="nav flex-column list-group list-group-flush">
<li className={`nav-item ${isActive("/dashboard") && "bg-primary"}`}>
<Link to="/admin/dashboard" className="nav-link text-white opacity-75 hover-opacity-100">
Dashboard
</Link>
</li>
<li className={`nav-item ${isActive("/categories") && "bg-primary"}`}>
<Link to="/admin/categories" className="nav-link text-white opacity-75 hover-opacity-100">
Categories
</Link>
</li>
<li className={`nav-item ${isActive("/products") && "bg-primary"}`}>
<Link to="/admin/products" className="nav-link text-white opacity-75 hover-opacity-100">
Products
</Link>
</li>
</ul>
<div className="mt-5 px-3">
<button onClick={handleLogout} className="btn btn-outline-danger btn-sm w-100">Logout</button>
</div>
</div>
</nav>
<main className="col-md-9 ms-sm-auto col-lg-10 px-md-4 main-content">
<Outlet />
</main>
</div>
</div>
);
}
export default DashboardLayout

No comments:
Post a Comment