Repository navigation
Description
Version
void 1.8.0, @void/react 1.8.0
Problem
Link already works out three things about itself:
- current: it points to this page, so it gets
aria-current="page"anddata-void-active. - active: with
activeMatch="prefix", it points to this page or a parent of it, so it getsdata-void-active. - pending: a visit to its destination is loading, so it gets
data-void-pending.
That's enough to style the <a> itself with CSS. But apps can only read that state as DOM attributes, so anything else has to repeat the matching:
- A wrapper that takes the state as a prop. shadcn's
SidebarMenuButtonrenders the link throughrender={<Link />}and styles itself, its icon and its tooltip from anisActiveprop.data-void-activelands on the link, not on a prop. - Code that isn't a link. A page header that shows the label of the active sidebar link, a breadcrumb, or a tab bar's sliding indicator all need the active link as a value.
- Content inside the link. Swapping an icon for a spinner while the link is pending, or a filled icon for an outline one while it's active, needs a CSS selector on the parent for each case.
So apps write their own check, and it drifts from Link's rules:
import { Link, useNavigation, useRouter } from '@void/react';
// Ignores the query and doesn't decode the path the way Link does.
function isActive(path: string, href: string, home: string) {
return path === href || (href !== home && path.startsWith(`${href}/`));
}
function SidebarItem({ href, label, home }: { href: string; label: string; home: string }) {
const { path } = useRouter();
const navigation = useNavigation();
// Also compares the path only, so it misses the query, the method and the hash.
const pending = navigation.state === 'loading' && navigation.location?.pathname === href;
return (
<SidebarMenuButton isActive={isActive(path, href, home)} render={<Link href={href} />}>
{pending ? <Spinner /> : <Icon />}
{label}
</SidebarMenuButton>
);
}
function PageTitle({ links, home }: { links: { href: string; label: string }[]; home: string }) {
const { path } = useRouter();
return <h1>{links.find((link) => isActive(path, link.href, home))?.label}</h1>;
}Proposal
1. A hook that takes the same values as Link.
const { current, active, pending } = useLinkStatus(href, { method, data, activeMatch });currentistruewhenLinkwould setaria-current.activeistruewhen it would setdata-void-active.pendingistruewhen it would setdata-void-pending.
The options keep Link's prop names, so the same values go to both. The result would be a LinkStatus, named like the FormStatus that useForm()'s state is built on, with the same pending.
Every adapter's Link already passes its router, navigation and resolved link to linkActiveAttributes() and linkPendingAttributes() from void/pages-client. The hook would be a thin wrapper around those two, with no new matching rules:
export function useLinkStatus(href: string, { method, data, activeMatch }: LinkStatusOptions = {}) {
const router = useContext(RouterContext);
const navigation = useContext(NavigationContext);
const link = useMemo(() => resolveLink({ href, method, data }), [href, method, data]);
return useMemo(() => {
const active = linkActiveAttributes(router, link, activeMatch);
return {
current: 'aria-current' in active,
active: 'data-void-active' in active,
pending: 'data-void-pending' in linkPendingAttributes(router, navigation, link),
};
}, [router, navigation, link, activeMatch]);
}The example above becomes:
function SidebarItem({ href, label }: { href: string; label: string }) {
const { active, pending } = useLinkStatus(href, { activeMatch: 'prefix' });
return (
<SidebarMenuButton isActive={active} render={<Link href={href} activeMatch="prefix" />}>
{pending ? <Spinner /> : <Icon />}
{label}
</SidebarMenuButton>
);
}2. A render prop on Link's children that receives the same object, for content inside the link without the hook's repeated href:
<Link href="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/admin/users" activeMatch="prefix">
{({ active, pending }) => (pending ? <Spinner /> : active ? <UsersFilledIcon /> : <UsersIcon />)}
</Link>3. A plain function for matching several hrefs at once, since hooks can't be called in a loop, as PageTitle above needs. It would take the router, so it works in any adapter:
import { isLinkActive } from 'void/pages-client';
function PageTitle({ links }: { links: { href: string; label: string }[] }) {
const router = useRouter();
return <h1>{links.find((link) => isLinkActive(router, link.href, { activeMatch: 'prefix' }))?.label}</h1>;
}That one is the existing linkActiveAttributes() with a boolean result and an href instead of a resolved link. isLinkPending(router, navigation, href) would match it.
Vue, Solid and Svelte would each get (1) and (2) in their own form: a computed ref, an accessor, a store, and a scoped slot or snippet.
Elsewhere
- TanStack Router:
useMatchRoute()matches any route byto, withfuzzyfor nested routes andpending: truefor the location being loaded.Linkpasses{ isActive, isTransitioning }to its children, andcreateLink()lets a custom component be the link and receiveactiveProps. - React Router:
useMatch()matches a pattern, andNavLinkpasses{ isActive, isPending, isTransitioning }toclassName,styleandchildren. - Vue Router:
useLink()returnsisActiveandisExactActive, the same split asactiveandcurrenthere. - Next.js:
useLinkStatus()returns{ pending }inside aLink's children. There's no active state, so apps compareusePathname()by hand.
Scope
(1) covers wrappers and content inside the link; (3) covers matching a list of links; (2) is a convenience over (1). I'd start with (1) and (3), which share all their logic with Link, and add (2) if you want it. I'm happy to open a PR, with tests that check each value agrees with Link's attributes for exact, prefix, query, method and pending cases.
Follows up on #676.
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Activity