Development / Web & Mobile Development
How To Set Active Navbar Menu Using Next.j
P
Prem 1 Min Read
1st Step: Create a Navbar Routes Component
Create Scalable, Responsive Interfaces with Next.js
âuse clientâ
codeMSI Editor
import React from âreactâ
const guestRoutes = [
{
icon: MdDashboard,
label: âhomeâ,
href: â/doctordashboardâ
},
{
icon: FaCartShopping,
label: â setavailability â,
href: â/ setavailability â
},
]
const NavbarRouts = () => {
const routes = guestRoutes;
return (
<div className=âflex text-gray-600 flex-col w-fullâ>
{
routes.map((route) => (
<NavbarItem
key={route.href}
icon={route.icon}
label={route.label}
href ={route.href}
/>
))
}
</div>
)
}
export default NavbarRoutes;2nd Step: Creates a Navbar Item Component
âuse clientâ
javascriptMSI Editor
import React from âreactâ;
import { IconType } from âreact-iconsâ;
import { usePathname, useRouter } from ânext/navigationâ;
interface NavbarItemProps {
icon: IconType;
label: string;
href: string;
}
const NavbarItem = ({ icon: Icon, label, href }: NavbarItemProps) => {
const pathname = usePathname();
const router = useRouter();
console.log(pathname, âdocotorâ)
const isActive =
(pathname === â/â && href === â/â) ||
pathname === href ||
pathname?.startsWith(`/${href}`);
const onClick = () => {
router.push(href);
// router.push(`doctor/${href}`);
};
return (
<div>
<button
onClick={onClick}
type=âbuttonâ
className={`flex items-center text-gray-400 text-sm py-4 p-5 space-x-2 ${
isActive
? â w-full cursor-pointer border-r-2 border-sky-400 bg-sky-50/90 font-semibold font-sans transition duration-300 text-sky-500 text-smâ
: â
}`}
>
<div className={`text-gray-400Â ${isActive ? âtext-sky-500âł :ââ}`}>
<Icon size={20} /> {/* Adjust the size as needed */}
</div>
<div >
{label}
</div>
</button>
</div>
);
};
export default Navbar Item;Reader Responses
