-
-
Notifications
You must be signed in to change notification settings - Fork 175
Description
In the current implementation of Link with asChild, the child element does not inherit most of the props passed to Link. For example, when using className, it doesn’t get applied to the child node.
Relevant source:
wouter/packages/wouter/src/index.js
Line 233 in cf9ba61
| ? cloneElement(children, { onClick, href }) |
This pattern—where asChild lets the child element behave as the rendered tag—is becoming more common (e.g., React Aria / Jacob Paris). The expectation is that the child receives all props passed to the parent Link.
Here's a practical example of why this matters:
import type { HTMLAttributes, RefAttributes } from 'react';
import { Link as WouterLink, type LinkProps as WouterLinkProps } from 'wouter';
function NoHrefLink({href, ...props}) {
return <a {...props} />
}
export type LinkProps = Omit<WouterLinkProps, 'asChild'> & HTMLAttributes<HTMLAnchorElement> & RefAttributes<HTMLAnchorElement>;
// Custom wrapper around wouter's Link
export function Link(props: LinkProps) {
const { children, to, href = to!, ...rest } = props;
return (
<WouterLink {...rest} href={href} asChild>
<NoHrefLink>{children}</NoHrefLink>
</WouterLink>
);
}Then used like this:
...
<Link href="/example" className="text-blue-500">
<span>Click me</span>
</Link>
...You’d expect the className to be applied to the tag, but it’s lost. This breaks encapsulation and makes it harder to build reusable wrappers around Link.
Edit: custom link component example updated