Last active
June 15, 2020 18:17
-
-
Save iamvanja/a9e0926d1b4894270a0d965ad13aaa05 to your computer and use it in GitHub Desktop.
Access child method from a parent in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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