Call one child method from anoher child

by amrendra kumar

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 Child1 extends React.Component {

/* componentDidMount() {
    this.props.onRef(this)
}
  componentWillUnmount() {
    this.props.onRef(null)
  }
 */  
  render() {
  return (
  	<div>
       <button onClick={this.props.onClick}>Click child2 method</button>
  	</div>
  	)
  }
}


class Child2 extends React.Component {
  
  method() {
    console.log('child2')
  }
  render() {
    return <h1>Hello World!</h1>
  }
}

class Parent extends React.Component {
  onClick = () => {
    this.child2.method() 
  };
  render() {
    return (
      <div>
        <Child1 onClick={this.onClick.bind(this)}/>
        <Child2 ref={child2 => this.child2 = child2} />
      </div>
    );
  }
}

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