next.js: Next 9 - Using functional components as child of causes ref-warnings

Bug report

Describe the bug

Using a functional component as a child of <Link/> causes:

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

This happened only after upgrading from v8 => v9.

To Reproduce

Reproduction repo: https://github.com/nickluger/nextjs-link-ref-functional-comp-warning

Expected behavior

<Link/> should work with functional components, too / not show a warning.

System information

  • Version of Next.js: 9.0.1

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 121
  • Comments: 57 (6 by maintainers)

Commits related to this issue

Most upvoted comments

You could try muting it temporarily , like:

// TODO: Muting error, fix as soon as zeit/next.js/issues/7915 resolved
const originalError = console.error;

console.error = (...args) => {
  if (/Warning.*Function components cannot be given refs/.test(args[0])) {
    return;
  }
  originalError.call(console, ...args);
};

Wrap all functional components used within a Link manually? Shouldn’t there be a easier, less repetitive solution for this? At least something like <Link href="/" forwardRef>...</Link>?

Same here. I am having error If I use custom component like this:

        <Link href="/href">
          <Button
            type="custom"
            color="#FCFCFC"
          >
             buttonText
          </Button>
        </Link>

This is only happening when you use a component as a child. These don’t give a warning for example:

        <Link href="/href">
          <button
            type="custom"
            color="#FCFCFC"
          >
            buttonText
          </button>
        </Link>

        <Link href="/href">
          <a>
            <Button
              type="custom"
              color="#FCFCFC"
            >
              buttonText
            </Button>
          </a>
        </Link>

I was watching the NextJS conference the other day thinking “Wow Next is the future”. I really like Next and the Vercel ecosystem and I want to honestly be able to say that and be an advocate for Next. However, issues like these being closed and not addressed make it hard to do so. I’ve seen this type of pattern multiple times throughout the issues here, specifically with the Router.

There’s 3 solutions to this problem from the user side and none of them are great DX.

  1. The recommended way React.forwardRef. wrap the component in React.forwardRef. This can be very repetitive
  2. Wrap the functional component in a tag like div, span, a, etc.
  3. Instead of Link, pull in useRouter and use router.push

No matter which solution you use, they’re all strange and require comments linking to this issue or the docs to explain to coworkers/contributors why its needed to prevent accidental removal/cleanup.

I think this issue should be reopened for discussion.

Following @hill84’s suggestion was a nice workaround:

const ButtonLink: FC<ButtonLinkProps> = ({ children, href, ...props }) => (
  <Link href={href}>
    <><Button link {...props}>{children}</Button></>
  </Link>
);

If you use <Link/> to wrap your custom component, you could forward ref like this:

const CustomComponent = React.forwardRef(function CustomComponent(props, ref) {
  return (
    <div/>
  );
});
<Link href={"/"}>
  <CustomComponent/>
</Link>

The warning goes away.

@machineghost Be nice - there are human people on the receiving end of your words.

Warning does go away when using react fragment, but in tat case link doesn’t work for me

I recently came across this issue and the way i solved is like this:

<Link href="/">
    <>
        <CustomComponent />
    </>
</Link>

So React Fragment seems to work in this case.

Why is this ref even needed? Is it to guarantee the correct placement of the href in the underlying wrapped component when passHref is used in the <Link />?

This is super annoying as my custom <Button /> component has the <a> at the root and I can see it’s getting href applied to it correctly anyway… I’d much rather have it enforced that you need your underlying custom component to have the anchor at the root and avoid this whole ref design desicion.

React.forwardRef is a horribly cumbersome thing to force people to implement and is playing hell with my linters 😞

Yes agree with @nickluger, it’s a pain to do this manually for all the components inside a Link.

Why is this issue closed? Was it solved? If so, where? I solved it with the <div></div> trick, but still seems hacky.

@th0th You should wrap your component in React.forwardRef. Like this one:

import React from 'react'
import Link from 'next/link'

const CustomComponent = React.forwardRef((props, ref) => (
  <a ref={ref} {...props}>
    Click
  </a>
))

export default () => (
  <Link href='/' passHref>
    <CustomComponent/>
  </Link>
)

Following @hill84’s suggestion was a nice workaround:

const ButtonLink: FC<ButtonLinkProps> = ({ children, href, ...props }) => (
  <Link href={href}>
    <><Button link {...props}>{children}</Button></>
  </Link>
);

I use <><Component/></> but Link can not action. I have to use <div></div> instead of.

This is a small pain in the butt every time you need to use a Link. Most components are functional components nowadays. Wrapping in <a> seems to be the most straightforward solution for most cases. I really think the nextjs team should think of a more convenient API though.

I recently came across this issue and the way i solved is like this:

<Link href="/">
    <>
        <CustomComponent />
    </>
</Link>

So React Fragment seems to work in this case.

Works for me aswell. Wondering if it has any implications…

+1 for this issue being re-opened. In the majority of cases Link is used to wrap a functional component, and using forwardRef in each component is not practical. Is there a reason the core team isn’t open to implementing one of the suggested solutions?

Anyway we can contact the core team so Link is usable again?

Didn’t realize there are some issues like this lurking in NextJS. And by issue, I mean how the primary concern in this matter is seen as nothing to care about.

import NextLink from "next/link";

function LinkWrap({ children, refAs, ...props }, ref) {
  if (refAs) {
    props[refAs] = ref;
  }
  return (
    <>
      {React.isValidElement(children)
        ? React.cloneElement(children, props)
        : null}
    </>
  );
}

const LinkWrapper = React.forwardRef(LinkWrap);

function Link({ refAs, children, ...props }) {
  return (
    <NextLink {...props}>
      <LinkWrapper refAs={refAs}>{children}</LinkWrapper>
    </NextLink>
  );
}

and use created Link component instead of next.js one

I suggest a solution where a function returns an object with props instead of a component :

const propsUserBtn = user => ({
    className: "h-10 w-10 font-black rounded-full bg-orange-200 text-teal-700",
    title: user.first_name + ' ' + user.last_name,
    children: (user.first_name.charAt(0) + user.last_name.charAt(0)).toUpperCase()
})
<Link href='/profile'>
    <button { ...propsUserBtn(user) } />   
</Link>

Checked, it works!

If I wrap the functional component in <a></a> it works fine with no forwardRef… and I’ve been using this method for years - does this break proper internal routing in some way I’m not seeing?

<Link href="/internal-link"><a><MyFunctionalComponent/></a></Link>

I’ve just encountered this error today! Problem fixed with this guide https://nextjs.org/docs/api-reference/next/link#if-the-child-is-a-function-component

I recently came across this issue and the way i solved is like this:

<Link href="/">
    <>
        <CustomComponent />
    </>
</Link>

EDITED: This solution is simultaneously genius AND dumb. Genius because progammer-rkt has found a clever and minimal solution to the problem … but dumb because that genius solution shouldn’t have been necessary in the first place.

Maybe this comes across as mean, but I truly think any competent React dev would understand that when you make a component for others to use, it shouldn’t be written it in a way that requires its children to be wrapped in meaningless fragments.

Next version: 10.0.1. The problem still persists.

Should we reopen and rename this issue (@ijjk) or did someone already open a new one?

Same here. I am having error If I use custom component like this:

        <Link href="/href">
          <Button
            type="custom"
            color="#FCFCFC"
          >
             buttonText
          </Button>
        </Link>

This is only happening when you use a component as a child. These don’t give a warning for example:

        <Link href="/href">
          <button
            type="custom"
            color="#FCFCFC"
          >
            buttonText
          </button>
        </Link>

        <Link href="/href">
          <a>
            <Button
              type="custom"
              color="#FCFCFC"
            >
              buttonText
            </Button>
          </a>
        </Link>

This will most likely throw a console error:

Warning: validateDOMNesting(...): <a> cannot appear as a descendant of <a>.

@progammer-rkt @huntedman @maksimf Just keep in mind that passHref wont work with this solution…

What about this solution using a react fragment as a bearing wrapper?

import React, { Fragment, useRef } from 'react';
import { MyFunctionalComponent } from './my-functional-component';

const App = props => {
  const myRef = useRef();

  return ( 
    <Link href={href}>
      <Fragment>
          <MyFunctionalComponent ref={myRef} />
      </Fragment>
    </Link>
  );
}

Where <MyFunctionalComponent> forwards the ref:

import React, { forwardRef } from 'react';

const MyFunctionalComponent = forwardRef(props, ref) => (
  <div ref={ref} />
);

This doesn’t add any additional HTML wrapper in the output (<div />) and should not trigger any related error.

If I wrap the functional component in <a></a> it works fine with no forwardRef… and I’ve been using this method for years - does this break proper internal routing in some way I’m not seeing?

<Link href="/internal-link"><a><MyFunctionalComponent/></a></Link>

yep this worked for me too!

Wrapping it in a div tag worked, but it didn’t render the Links anchor tag which could mess up SEO. Instead, I made a custom Link wrapper which wraps the component in an anchor tag- as described here. https://jasonwatmore.com/post/2021/05/31/next-js-make-the-link-component-work-like-react-router-link

@Vadorequest I’ve added more details to my previous comment.