Ref to a child component through HOC

by jackrugile

HTML

<script src="https://unpkg.com/[email protected]/dist/react-with-addons.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>
<div id="root"></div>

Babel + JSX

class Child extends React.Component {
  componentDidMount() {
    this.props.onRef(this)
  }
  componentWillUnmount() {
    this.props.onRef(null)
  }
  method() {
    console.log('do stuff')
  }
  render() {
    return <h1>Hello World!</h1>
  }
}

class Parent extends React.Component {
  onClick = () => {
    this.child.method() // do stuff
  };
  render() {
    return (
      <div>
        <Child onRef={ref => (this.child = ref)} />
        <button onClick={this.onClick}>Child.method()</button>
      </div>
    );
  }
}

ReactDOM.render(<Parent />, document.getElementById('root'))