Skip to content

Instantly share code, notes, and snippets.

@beardlessman
Created June 22, 2018 08:42
Show Gist options
  • Save beardlessman/7430c23a991475e072c8cd625638819d to your computer and use it in GitHub Desktop.
Save beardlessman/7430c23a991475e072c8cd625638819d to your computer and use it in GitHub Desktop.
REACT How to call child component method from parent
/* Child.js */
import React from 'react'
class Child extends React.Component {
componentDidMount() {
this.props.onRef(this)
}
componentWillUnmount() {
this.props.onRef(undefined)
}
method() {
window.alert('do stuff')
}
render() {
return <h1>Hello World!</h1>
}
}
export default Child;
/* Parent.js */
import React from 'react'
import Child from './Child'
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>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment