src/components/sidebar/sidebar.tsx
import React, { useEffect } from "react";
import { Icon } from "@iconify/react";
import { Link, useNavigate, useLocation } from "react-router-dom";
import {
sidebarItems1,
sidebarItems2,
sidebarItems3,
applicantSidebarItems,
traineeSidebarItems,
} from "./sidebarItems";
import "./navslide.css";
import TokenExpirationHandler from "../../utils/tokenExpirationHandler";
const Sidebar = ({ expanded, setExpanded }) => {
const navigate = useNavigate();
const location = useLocation();
const roleName = localStorage.getItem("roleName");
useEffect(() => {
const isTokenValid = TokenExpirationHandler.validateToken();
if (!isTokenValid) {
navigate("/login");
}
}, [location.pathname, navigate]);
const items =
roleName === "applicant"
? applicantSidebarItems
: roleName === "trainee"
? traineeSidebarItems
: [...sidebarItems1, ...sidebarItems2];
const handleLogout = () => {
localStorage.clear();
navigate("/login");
};
// Function to check if the current item is active based on the current path
const isActive = (path) => {
if (path.startsWith("/")) {
return location.pathname === path;
} else {
return location.pathname.endsWith(path);
}
};
return (
<div
className={` ${
expanded ? "w-[16rem]" : "w-[4rem]"
} fixed dark:bg-dark-bg bg-white border-r transition-width duration-300 h-full overflow-scroll z-50`}
>
<button
onClick={() => setExpanded(!expanded)}
className="p-1.5 rounded-lg bg-gray-50 absolute top-2 right-2 z-20"
>
<Icon
icon={expanded ? "material-symbols:menu-open" : "mdi:menu-close"}
color="#000"
/>
</button>
<div className="pt-12 pb-12 mb-20">
<ul className="pl-4">
{items.map((item, index) => (
<li
key={index}
className={`flex items-center ${
isActive(item.path)
? "bg-gray-700 text-[#56C770]"
: "dark:text-white text-black hover:text-[#56C770]"
}`}
>
<Link to={item.path} className="p-1 flex items-center">
<span className="mr-3">{item.icon}</span>
{expanded && <span>{item.title}</span>}
</Link>
</li>
))}
</ul>
{/* Render sidebarItems3 at the bottom */}
<ul className="px-4 mt-4">
{sidebarItems3.map((item, index) => (
<li
key={index}
className={`flex items-center ${
isActive(item.path)
? "bg-gray-700 text-[#56C770]"
: "dark:text-white text-white hover:text-[#56C770]"
}`}
>
<Link to={item.path} className="p-1 flex items-center">
<span className="mr-3">{item.icon}</span>
{expanded && <span>{item.title}</span>}
</Link>
</li>
))}
</ul>
<button
onClick={handleLogout}
className="flex items-center p-1 font-semibold hover:font-bold text-black dark:text-white focus:outline-none hover:text-[#56C770] mt-4 ml-4"
>
<Icon icon="hugeicons:logout-circle-02" className="mr-3" />
{expanded && <span>Logout</span>}
</button>
</div>
</div>
);
};
export default Sidebar;