Navigation
Learn how to navigate between pages in dinou.
Programmatic Navigation
To navigate programmatically between pages you do:
// src/route/page.tsx
"use client";
export default function Page() {
const handleNavigate = () => {
window.location.assign("/route-2?foo=bar");
};
return (
<div>
<button onClick={handleNavigate}>Go to /route-2</button>
</div>
);
}
usePathname Hook
The usePathname
hook returns the current URL pathname and updates it when the user navigates with the browser back/forward buttons.
Definition
import { useState, useEffect } from "react";
export function usePathname(): string {
const [pathname, setPathname] = useState<string>("");
useEffect(() => {
setPathname(window.location.pathname);
const handleRouteChange = () => {
setPathname(window.location.pathname);
};
window.addEventListener("popstate", handleRouteChange);
return () => {
window.removeEventListener("popstate", handleRouteChange);
};
}, []);
return pathname;
}
Usage Example: Active Navigation Item
You can use usePathname
to highlight the current active menu item based on its href
.
"use client";
import { usePathname } from "@/hooks/use-pathname";
const links = [
{ href: "/home", label: "Home" },
{ href: "/about", label: "About" },
{ href: "/contact", label: "Contact" },
];
export default function NavMenu() {
const pathname = usePathname();
return (
<nav className="flex space-x-4">
{links.map((link) => {
const isActive = pathname === link.href;
return (
<a
key={link.href}
href={link.href}
className={isActive ? "text-blue-600 font-semibold" : "text-gray-700"}
>
{link.label}
</a>
);
})}
</nav>
);
}
This helps you keep your navigation UI in sync with the current route.