Home > Net >  Render Custom Component Inside NextJS Link
Render Custom Component Inside NextJS Link

Time:10-06

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?

CodePudding user response:

The problem is not from the next/link, the problem is from the import, This error indicates that there is no named export "ArrowSmRightIcon" in the package heroicons-react I believe what you're looking for is ArrowSmRight

import { ArrowSmRight  } from 'heroicons-react'

Plus the package is deprecated as stated by the maintainers:

This package has been deprecated

Author message:

Official Heroicons V1 released. Please use the following for future > projects: https://www.npmjs.com/package/@heroicons/react

the currently maintained version is: https://www.npmjs.com/package/@heroicons/react

  • Related