Skip to content

Instantly share code, notes, and snippets.

@iamvanja
Last active June 15, 2020 18:17
Show Gist options
  • Save iamvanja/a9e0926d1b4894270a0d965ad13aaa05 to your computer and use it in GitHub Desktop.
Save iamvanja/a9e0926d1b4894270a0d965ad13aaa05 to your computer and use it in GitHub Desktop.
Access child method from a parent in React
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
class Child extends PureComponent {
componentDidMount() {
const { getMethod } = this.props;
// Pass child method to the parent by calling parent getter
// This could be something more general (`getMethods` where array/object of methods is passed)
getMethod(this.handleChildMethod);
}
handleChildMethod = () => {
console.log('child method!');
}
render() {
return (
<div>Child</div>
);
}
}
Child.propTypes = {
getMethod: PropTypes.func.isRequired
}
export default Child
import React, { PureComponent } from 'react'
import Child from './Child'
class Parent extends PureComponent {
acceptMethods = (childMethod) => {
// Parent stores the method that the child passed
this.childMethod = childMethod
}
render() {
return (
<div>
{/* Pass callback getter to store child method in the parent component */}
<Child
shareMethods={this.acceptMethods}
/>
{/* Call the child method directly! */}
<button onClick={this.childDoAlert}>Click</button>
</div>
);
}
}
export default Parent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment