Skip to content

Using a ref from a class component #29

@raphaelbs

Description

@raphaelbs

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions