connect-backbone-to-react icon indicating copy to clipboard operation
connect-backbone-to-react copied to clipboard

Using a ref from a class component

Open raphaelbs opened this issue 2 years ago • 0 comments

I have a class component that has a method inside of it:

class MyClassComponent extends Component {
  method1() {}
  render() {
    // ...
  }
}

And I have a snippet that saves the reference of the class component to be used later (doSomething):

render() {
  this._componentInstance = React.createRef();
  // Create and render the nav menu.
  ReactDOM.render(
    <MyClassComponent ref={this._componentInstance} />,
    domNode
  );
}

doSomething() {
  // calls the method from the instance
  this._componentInstance.current.method1();
}

That works because according to the docs,

When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current.

Problem is, when I add the HoC, the ref stops working:

class MyClassComponent extends Component {
  method1() {}
  render() {
    // ...
  }
}
export default connectBackboneToReact(mapModelsToProps, { withRef: true })(MyClassComponent)

Then every time this._componentInstance.current.method1(); runs, it says the this._componentInstance.current is undefined.

raphaelbs avatar Sep 27 '22 23:09 raphaelbs