T
TanStack8mo ago
flat-fuchsia

custom link inside component with asChild

i can create a customLink provided by the examples in the doc. But when i want to use this link inside a custom component, lets say a shadCN dropdown menu item with asChild, it throws an error that i should provide an forward ref. Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? Basic example
interface LinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {
className?: string
}

const BasicLinkComponent = React.forwardRef<HTMLAnchorElement, LinkProps>(
(props, ref) => {
return <a ref={ref} {...props} />
}
)

const CreatedLinkComponent = createLink(BasicLinkComponent)

export const Link: LinkComponent<typeof BasicLinkComponent> = (props) => {
return <CreatedLinkComponent {...props} />
}
interface LinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {
className?: string
}

const BasicLinkComponent = React.forwardRef<HTMLAnchorElement, LinkProps>(
(props, ref) => {
return <a ref={ref} {...props} />
}
)

const CreatedLinkComponent = createLink(BasicLinkComponent)

export const Link: LinkComponent<typeof BasicLinkComponent> = (props) => {
return <CreatedLinkComponent {...props} />
}
<DropdownMenuItem asChild>
<Link
>
<EyeIcon />
View
</Link>
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link
>
<EyeIcon />
View
</Link>
</DropdownMenuItem>
How can i make the createLink function work so my Link component accepts a ref? const const Link = React.forwardRef<HTMLAnchorElement, LinkComponent<typeof BasicLinkComponent>>((props, ref) => { This doesn't work.
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?