React: Ref is not passed through a HOC

Created on 6 Apr 2017  Â·  8Comments  Â·  Source: facebook/react

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

What is the current behavior?
The parent component of a child component wrapped in a HOC cannot assign a ref attribute to the child component. The ref attribute instead refers to the HOC.

In order for the parent component to reference the child component, it must use some of the below popular workarounds:
onRef prop
https://github.com/kriasoft/react-starter-kit/issues/909

innerRef prop
https://github.com/styled-components/styled-components/pull/122

getInstance func
https://github.com/christianalfoni/formsy-react/issues/308

What is the expected behavior?
In accordance with the decorator pattern, a child wrapped with a HOC should not be less accessible than a child not wrapped with a HOC. It is expected that the ref attribute pass through the HOC.

Duplicate

Most helpful comment

@ggd543 Foo and App is not HOC ...

All 8 comments

Thanks for the request @Deepblue129, there's an existing issue at https://github.com/facebook/react/issues/4213 tracking this. If you have any additional input, please share it there!

you can use callback instead. here is example

class Foo extends React.Component {
  componentDidMount() {
     this.props.onRef(this);
  }

  render() {
     return 
  }
}
export default Foo;
import Foo from './foo';

class App extends React.Component {
   render() {
     <Foo onRef={foo => this.foo=foo} />
  } 
}

@ggd543 Foo and App is not HOC ...

@ggd543 Thanks a lot!

@ggd543 Dam dude !! this worked for me.

You don't need this workaround now — React 16.3 and later supports ref forwarding.

https://reactjs.org/docs/forwarding-refs.html

just want to suggest little HOC

const withRef = Component => React.forwardRef((props, ref) => <Component {...props} forwardedRef={ref} />);

@gaearon What should one do when the third party HOC that's being used does not support ref forwarding?

Was this page helpful?
0 / 5 - 0 ratings