0

If I have a class-based component:

class MyComponent extends React.Component {
    state = {...}
    constructor(props) {...}
    functionIWantToCall() {...}
    render() {...}
}

That is incorporated into the DOM something along the lines of:

<div id="parent-div-with-controls">
  .... (some control elements) ....
  <MyComponent {...props}/>
</div>

Is there a way that I can call a method defined in MyComponent from parent-div-with-controls?

I'm imagining the 'react equivalent' (if such a thing exists) of this:

const myComponent = new MyComponent()
myComponent.functionIWantToCall()

Or alternatively, is this something that I would never want to do in React?

Zach Smith
  • 8,458
  • 13
  • 59
  • 133

1 Answers1

0

You can use a ref to have a "connection" with the instance in MyComponent:

In your parent component, do something like:

class Parent extends React.Component {

  innerComponentInstance = React.createRef()

  // sample place where to "contact" the child component
  componentDidUpdate() {
    this.innerComponentInstance.functionIWantToCall()
  }

  render() {
    <MyComponent ref={ this.innerComponentInstance } />
  }

}
0xc14m1z
  • 3,675
  • 1
  • 14
  • 23