Jeremy Gottfried
Jeremy Gottfried

Reputation: 1201

Does React not explicitly export forwardRef?

UPDATE: There is nothing wrong with the implementation below. The error was due to a react-redux upgrade, as redux now relies on functional components instead of class components.

import React, { forwardRef } from 'react'

const DivWithRef = forwardRef((props, ref) => {
  return(
    <div ref={ref} {...props}>
      {props.children}
    </div>
  )
})
class AClassComponent extends Component {
  render() {
    return (
      <DivWithRef ref={me => this.node = me} />
    ) 
  }
}

When I try this I get the error:

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

Does react not explicitly export forwardRef?

I have been using this code for a while, and it never caused any issues. After I updated to React 16.8, I started getting the warning above, but my app can still access the DOM Ref even though react claims it shouldn't be able to.

Upvotes: 3

Views: 7706

Answers (3)

Jeremy Gottfried
Jeremy Gottfried

Reputation: 1201

I answered it on my own. It's not a problem with my implementation. Callback refs are a valid implementation, as explained here: reactjs.org/docs/refs-and-the-dom.html#callback-refs

The reason for the error is that the latest version of react-redux uses functional components instead of class components. After I updated to react-redux, my refs on connected components return the error.

Upvotes: 1

Muhammad Mehar
Muhammad Mehar

Reputation: 1055

The second ref argument only exists when you define a component with React.forwardRef call.

React.forwardRef

Upvotes: 0

Josep
Josep

Reputation: 13071

You want to do this instead:

constructor() {
  this.node = React.createRef();
}
// more code
render() {
  return <DivWithRef ref={this.node} />;
}

The rest of your code is correct.

Upvotes: 3

Related Questions