How to fix the ‘Function components cannot have refs. Did you mean to use React.forwardRef()?’ error with React and JavaScript?

Sometimes, we want to fix the ‘Function components cannot have refs. Did you mean to use React.forwardRef()?’ error with React and JavaScript.

In this article, we’ll look at how to fix the ‘Function components cannot have refs. Did you mean to use React.forwardRef()?’ error with React and JavaScript.

How to fix the ‘Function components cannot have refs. Did you mean to use React.forwardRef()?’ error with React and JavaScript?

To fix the ‘Function components cannot have refs. Did you mean to use React.forwardRef()?’ error with React and JavaScript, we should call React.forwardRef with the function component that we want to assign the ref to.

For instance, we write:

import React from "react";

const Input = React.forwardRef(({ backgroundColor }, ref) => {
  return <input style={{ backgroundColor }} ref={ref} />;
});

export default function App() {
  const ref = React.useRef();

  React.useEffect(() => {
    ref.current.focus();
  }, []);

  return (
    <div>
      <Input backgroundColor="green" ref={ref} />
    </div>
  );
}

to create the Input function component and assign a ref to it.

We set the ref prop to the ref parameter in the Input component.

Then in App, we create a ref with the useRef hook and assign the ref prop to the ref.

And we call ref.current.focus in the useEffect callback.

Now the input should be focused when we load the page.

Conclusion

To fix the ‘Function components cannot have refs. Did you mean to use React.forwardRef()?’ error with React and JavaScript, we should call React.forwardRef with the function component that we want to assign the ref to.