Skip to content

Link with asChild should forward props to its child element #536

@inakiabt

Description

@inakiabt

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:

? 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions