I’m using @tanstack/react-router
file-based routing. I have links in my __root.tsx
element. Let’s say some of these links point to /route1
, /route2
, /route3
.
In my global scss file, I have a line like this, which disables links with property aria-current="page"
[aria-current="page"] {
pointer-events: none;
cursor: default;
text-decoration: none;
}
Whenever I’m on a page of that route, such as /route1
, the link is disabled, which is expected behavior. But, when I’m on a child route (route1/$id
), the link is still disabled. This makes no sense to me, because I cannot navigate up the /route1
from the child route.
In Chrome’s inspect, the <Link>
element looks like this:
<a class="false active" href="/route1" data-status="active" aria-current="page">Route1</a>
and still includes those two properties, even though it’s not on the /route1
route anymore, it’s on a child route. Is this expected behavior? I assumed that aria-current="page"
prop would be undefined
when it’s on the child route, but it’s not.
Uncommenting the scss block above fixed it, but I would still like to have any a
elements with aria-current="page"
property have that behavior.
Is there any way to fix this and also keep the scss block?
As mentioned above, I was expecting aria-current="page"
to be removed from the /route1
link once I routed to a child page, but it’s only undefined
on neighbor routes, not child routes.
Michael Hsu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
In your case, the parent route (/route1) is still considered active when you are on a child route (/route1/$id), which is why aria-current=”page” is still applied to the parent . This is expected in some routing libraries, as they consider the parent route to be active when any of its children are active.
Here, modify your routing logic so that aria-current=”page” is applied only when the link matches the route exactly (not when it’s on a child route). Some routers (including TanStack/React Router) offer ways to differentiate between an exact route match and a broader match.
You can manually check if the current route is an exact match to disable the link. Here’s a general approach using the useMatch hook from @tanstack/react-router.
import { Link, useMatch } from '@tanstack/react-router';
const Navbar = () => {
const isExactRoute1 = useMatch({
path: '/route1',
exact: true, // Only match /route1, not /route1/* (children)
});
return (
<nav>
<Link
to="/route1"
aria-current={isExactRoute1 ? 'page' : undefined}
>
Route1
</Link>
<Link
to="/route2"
aria-current={/* Similar logic for other routes */}
>
Route2
</Link>
</nav>
);
};
In this case, the aria-current=”page” attribute is only applied if you’re on /route1 exactly, and not on any child routes like /route1/$id.
for learning more about routing concepts in tanstack, official documentation.
https://tanstack.com/router/latest/docs/framework/react/guide/routing-concepts