Next.js Discord

Discord Forum

What is the appropriate way to apply an aria-current to a Link component?

Unanswered
Large garden bumble bee posted this in #help-forum
Open in Discord
Large garden bumble beeOP
Imagine that I have a component which will be a link.
function LinkButton = forwardRef<HTMLAnchorElement, LinkProps>(({ href, ...props }, ref) => {
  return <Link {...props} href={href} ref={ref} />
});

Now, I want to apply a aria-current="page" if the href prop matches the current route. However, I'm not sure what the appropriate way to do this is
For one, the docs say that the path can be a string or an object. https://nextjs.org/docs/app/api-reference/components/link
The problem here is: how do I test that the current route matches? Is there a built in way in Next.js?

6 Replies

how do I test that the current route matches? Is there a built in way in Next.js?
usePathname() with client component and then check if its the same pathname
Large garden bumble beeOP
what if it's an object though? Looks like that's an option too
well then you can check if its typeof thing === "string" and thats the pathname otherwise use thing.pathname
if your also wanting the search params in href, you can make use of useSearchParams
Large garden bumble beeOP
sure but there's no existing function to take something like
const href = {
  pathname: "/users/[id]",
  query: { id: "456" }
}

And coerce it into the string it will become to test it, right?
it seems like Node.js ships something, but I would also need this to work on the client