import { forwardRef } from 'react'
import Link from 'next/link'
import { Menu } from '@headlessui/react'
const MyLink = forwardRef((props, ref) => {
let { href, children, ...rest } = props
return (
<Link href={href}>
<a ref={ref} {...rest}>
{children}
</a>
</Link>
)
})
Trying to use this snippet from headless ui react docs that suggest this for Next.js users. i am discovering that i get TS errors on ref and href. thoughts? Is this a case where i would needed to use dangerouslySetInnerHTML?
Property 'href' does not exist on type '{ children?: ReactNode; }'.ts(2339)
ref={ref} error below this
(property) ClassAttributes<HTMLAnchorElement>.ref?: LegacyRef<HTMLAnchorElement> |
undefined
Type 'ForwardedRef<unknown>' is not assignable to type 'LegacyRef<HTMLAnchorElement> |
undefined'.
Type 'MutableRefObject<unknown>' is not assignable to type 'LegacyRef<HTMLAnchorElement>
| undefined'.
Type 'MutableRefObject<unknown>' is not assignable to type
'RefObject<HTMLAnchorElement>'.
Types of property 'current' are incompatible.
Type 'unknown' is not assignable to type 'HTMLAnchorElement | null'.ts(2322)
overall goal is to get keyboard accessibility headless supplies to work on my drop down
From what I understand, React.forwardRef takes two type params. The RefType and the Props Type (backwards from the function params, (props, rev)=>{})
You'll need to pass the correct params like this. Though I'm relatively inexperienced at this, the RefType should be HTMLAnchorElement because that's what you're rendering within the link, and that's the type of ref Menu.Item is passing. As for the Prop type I'm less sure, but I beleve it's the LinkProps from Next.js and the default HTMLProps<HTMLAnchorElement> as you'll need the href prop that's a URL not just a string from the LinkProps while you'll need the rest of the default anchor props as you'll be spreading them to the link.
Here's a link that helped me figure some of this out
const NextLink = forwardRef<HTMLAnchorElement, LinkProps & HTMLProps<HTMLAnchorElement> >(
({ href, children, ...rest }, ref) => {
return (
<Link href={href}>
<a ref={ref} {...rest}>
{children}
</a>
</Link>
);
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With