react-redux: react-redux v.7 doesn't allow refs on connected components

Do you want to request a feature or report a bug? Bug

What is the current behavior? When I updated to the latest version of react-redux, I started seeing the following warning on many of my connected components.

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

React doesn’t allow refs on functional components, so any components that were accessed with a ref in past react-redux versions are now broken.

What is the expected behavior? My connected components that were previously exposed with refs would still be able to have a ref.

Which versions of React, ReactDOM/React Native, Redux, and React Redux are you using? Which browser and OS are affected by this issue? Did this work in previous versions of React Redux? react v.16.8.6, react-dom v.16.8.6, react-redux v.7.0.3

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 18 (9 by maintainers)

Most upvoted comments

First, function components cannot have refs.

With React-Redux specifically:

  • in v5 and earlier, you have to add the withRef: true option to connect(), put a ref on the Connect(MyComponent) wrapper, and then call wrapperComponent.getWrappedInstance()
  • in v6 and v7, you have to add the forwardRef : true option to connect(), and the ref that you put on the Connect(MyComponent) wrapper will actually be the instance of MyComponent

If you are not supplying the forwardRef option in v6/7, then I would expect the ref to be applied to the internal wrapper component, which is now a function component, and thus you’re getting that error message.

So, make sure you’re passing {forwardRef : true} to connect(), and things should work okay.

Basically, change withRef to forwardRef, and then delete the .getWrappedInstance() part of componentRef.getWrappedInstance(). componentRef is your own component now.

Refs are never sent as props to the component, so it’s not possible to know if your caller has used them or not.

Yep. It’s an extra layer of wrapping, and refs are very rarely used.

There is a performance penalty and most folks don’t need it.