T
TanStack11mo ago
eastern-cyan

Link isActive on parent component

I need to pass isActive to the parent component of a Link. It is described here how to do it for a child component: https://tanstack.com/router/latest/docs/framework/react/guide/navigation#passing-isactive-to-children But I can't seem to figure out how I could check if the link is active at the parent component. Any help greatly appreciated!
TanStack | High Quality Open-Source Software for Web Developers
Headless, type-safe, powerful utilities for complex workflows like Data Management, Data Visualization, Charts, Tables, and UI Components.
From An unknown user
From An unknown user
6 Replies
exotic-emerald
exotic-emerald11mo ago
Assuming you need it for styling purposes, active Link components are passed the active class so if you're using tailwind, you can do this
<div className="has-[.active]:bg-[red]">
<Link to="/" className="[&.active]:font-bold">
Home
</Link>
</div>
<div className="has-[.active]:bg-[red]">
<Link to="/" className="[&.active]:font-bold">
Home
</Link>
</div>
eastern-cyan
eastern-cyanOP11mo ago
It's not for styling purposes. I need to pass an actual boolean prop to the parent.
exotic-emerald
exotic-emerald11mo ago
use the useMatches hook then
eastern-cyan
eastern-cyanOP11mo ago
Could you help me with an example? Like this?
const matches = useMatches();

<Parent
isActive={matches.some(
(match) => match.fullPath === "/some-path",
)}
>
<Link
to="/some-path"
>
...
</Link>
</Parent>
const matches = useMatches();

<Parent
isActive={matches.some(
(match) => match.fullPath === "/some-path",
)}
>
<Link
to="/some-path"
>
...
</Link>
</Parent>
exotic-emerald
exotic-emerald11mo ago
Sorry, it was the useMatchRoute hook instead. So assuming you're creating a reusable link component
import { Link, LinkProps, useMatchRoute } from '@tanstack/react-router';
import { ReactNode } from 'react';

export default function CustomLink({
to,
children,
}: {
to: LinkProps['to'];
children: ReactNode;
}) {
const matchRoute = useMatchRoute();
const params = matchRoute({ to });
const isActive = !!params;

return <Link to={to}>{children}</Link>;
}
import { Link, LinkProps, useMatchRoute } from '@tanstack/react-router';
import { ReactNode } from 'react';

export default function CustomLink({
to,
children,
}: {
to: LinkProps['to'];
children: ReactNode;
}) {
const matchRoute = useMatchRoute();
const params = matchRoute({ to });
const isActive = !!params;

return <Link to={to}>{children}</Link>;
}
Or with your example
const matchRoute = useMatchRoute();
const params = matchRoute({ to: "/some-path" });
const isActive = !!params;

<Parent>
<Link
to="/some-path"
>
...
</Link>
</Parent>
const matchRoute = useMatchRoute();
const params = matchRoute({ to: "/some-path" });
const isActive = !!params;

<Parent>
<Link
to="/some-path"
>
...
</Link>
</Parent>
eastern-cyan
eastern-cyanOP11mo ago
Thank you!

Did you find this page helpful?