Search code examples
reactjstypescriptcreate-react-app

Functional component with warning in development : Function components cannot be given refs. ...Did you mean to use React.forwardRef()?


I have a question regarding the use of a plugin that I created, and used in an application called HRnet (React 18).

I have no warning in development on the plugin side. But in development on the application side I always have this warning from the bundle.js (but not in production):

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

It's related to my plugin (no more warning when I comment my plugin), but I don't understand why.

My plugin is a dropdown, it is published on NPM, for the bundler I used Rollup, and lifting state up to pass the value.

NPM

plugin: https://www.npmjs.com/package/react-dropdown-component-library

CodeSandbox (updated)

Dropdown (plugin): https://codesandbox.io/s/dropdown-pybhpn?file=/src/lib/index.tsx

HRNet (app): https://codesandbox.io/s/hrnet-9xq0qv?file=/src/components/AddUseForm/index.tsx:8850-8851


Solution

  • This is probably because register from react-hook-form returns a ref, and it is required by that library that the component it is attached to connects it to the actual form node.

    However your dropdown is custom and doesn't use a base HTML element so you need to just not attach it instead. See https://react-hook-form.com/faqs/#Whatifyoudonthaveaccesstoref