react icon indicating copy to clipboard operation
react copied to clipboard

Ref is not passed through a HOC

Open PetrochukM opened this issue 9 years ago • 8 comments

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.

PetrochukM avatar Apr 06 '17 00:04 PetrochukM

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!

aweary avatar Apr 10 '17 15:04 aweary

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 avatar Apr 09 '18 07:04 ggd543

@ggd543 Foo and App is not HOC ...

arufian avatar Jun 27 '18 01:06 arufian

@ggd543 Thanks a lot!

Martinnord avatar Jul 17 '18 08:07 Martinnord

@ggd543 Dam dude !! this worked for me.

rollthecoder avatar Aug 16 '18 21:08 rollthecoder

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

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

gaearon avatar Aug 16 '18 22:08 gaearon

just want to suggest little HOC

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

titulus avatar Jan 10 '19 06:01 titulus

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

steric85 avatar Apr 07 '20 15:04 steric85