testing-library / react-testing-library

🐐 Simple and complete React DOM testing utilities that encourage good testing practices.

Home Page:https://testing-library.com/react

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Testing Link from react-router-dom throws a warning "Function components cannot be given refs"

PaulineNemchak opened this issue · comments

  • @testing-library/react version: ^14.0.0

  • Testing Framework and version: ^29.5.0

  • DOM Environment: jsdom: ^21.1.1

  • react: ^18.2.0

Relevant code or config:

<Link
  ref={linkRef}
  to={localizedHref}
  ...
>
  {children}
</Link>

What you did:

I tested a component that uses Link component from react-router-dom.

What happened:

All tests passed, but I received this warning:

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

But as I understand, it uses forwardRef and shouldn't cause this warning.

Reproduction:

Test component that uses Link from react-router.

Problem description:

It throws a warning to console but it probably shouldn't.

Suggested solution:

I don't have a solution

Hi @PaulineNemchak!
This warning is a React error and isn't related to us at all.
The reason you're getting that is because you're passing ref to the Link component.
In version 6 of react-router-dom, there's no ref prop AFAIR, in version 4 and 5, it's called innerRef IIRC.
You're probably getting this warning at runtime in your browser console too.
If that's not the case, please re-open this issue and attach a minimal reproduction via github/codesandbox so we'll be able to investigate.
Thanks.

@MatanBobi The problem is that Link is defined as: export declare const Link: React.ForwardRefExoticComponent<LinkProps & React.RefAttributes<HTMLAnchorElement>>;
and should have a ref prop (I don't see any errors related to this on localhost/prod or with linting)

You won't see it in prod because it's a warning, you'll only see it in localhost.
Since this isn't related to testing-library (as our code doesn't contain anything related to the Link component), I suggest asking a question in stackoverflow about this one or if you believe it's a bug, opening an issue for react-router-dom.

@MatanBobi just fyi, you were right. I was thinking that there's a problem with processing on some step (jest, testing library or bundler), but it turned out that there was a mock of the Link component that was not wrapped in forwardRef, which caused this warning. Sorry, I didn't notice it before.