Issue:
I have a component that should redirect users to a new page on click. I want to use Next's <Link>
component to take care of the route change.
However, I've noticed that the Link
component refuses to render if any of its children are not standard HTML elements (e.g., <div>
, <a>
, ...).
In the example below, the component I want to render is an icon from the heroicons
library.
MyPage.js
import Link from 'next/link'
import { ArrowSmRightIcon } from 'heroicons-react'
export default function MyPage() {
return(
<Link href='/targetPage'>
<ArrowSmRightIcon />
</Link>
)
}
Running the above renders the following error:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
Attempted solution:
I've found some advice online about having to create a custom component that using forwardRef
. I've implemented my custom component as:
IconLink.js
import NextLink from 'next/link'
import { forwardRef } from "react";
import { ArrowSmRightIcon } from 'heroicons-react'
const IconLink = forwardRef(({ href, prefetch, replace, scroll, shallow, locale, ...props }, ref) => {
return(
<NextLink
href={href}
replace={replace}
scroll={scroll}
shallow={shallow}
locale={locale}
passHref
>
<ArrowSmRightIcon ref={ref} {...props} />
</NextLink>
)
})
export default IconLink
MyPage.js
import IconLink from './IconLink';
export default function MyPage() {
return(
<IconLink
passHref
href='/targetPage'
/>
)
}
However, I still get the same error.
What should I do render a custom child component inside Next's <Link>
component?