-
SummaryI would like to highlight the active link. My index page contains some divs with anchor tags so there are several routes
I created a link component that should check if there is an exact match "use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
interface Props {
href: string;
title: string;
}
export default function NavigationLink({ href, title }: Props) {
const pathname = usePathname();
const [hash, setHash] = useState("");
useEffect(() => {
const updateHash = () => setHash(window.location.hash);
updateHash();
window.addEventListener("hashchange", updateHash);
return () => window.removeEventListener("hashchange", updateHash);
}, []);
const [basePath, anchor] = href.split("#");
const isSamePath = pathname === basePath;
const isSameAnchor = anchor ? hash === `#${anchor}` : hash === "";
const isActive = isSamePath && isSameAnchor;
return (
<Link href={href}>
{isActive}
</Link>
);
} Unfortunately this is not 100% correct yet. When visiting the app on Do you have any ideas how to fix this behaviour? If there is an already builtin NextJs solution for this please let me know! Additional informationNo response ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The CSS Edit: Always a harsh reminder that:
That means that a plain "use client";
import Link from "next/link";
import { usePathname, useSelectedLayoutSegment } from "next/navigation";
import { useEffect, useState } from "react";
interface Props {
href: string;
title: string;
}
export default function NavigationLink({ href, title }: Props) {
useSelectedLayoutSegment()
const pathname = usePathname();
const [hash, setHash] = useState("");
useEffect(() => {
setHash(window.location.hash);
});
const [basePath, anchor] = href.split("#");
const isSamePath = pathname === basePath;
const isSameAnchor = anchor ? hash === `#${anchor}` : hash === "";
const isActive = isSamePath && isSameAnchor;
return (
<Link href={href}>
{isActive.toString()}
</Link>
);
} This one works though 👀 |
Beta Was this translation helpful? Give feedback.
The CSS
:target
selector can do that, https://codepen.io/matude/pen/OQrryPEdit: Always a harsh reminder that:
That means that a plain
<a>
would do, but IIRC it doesn't play nicely with the fwd/back, might be wrong there.