Reputation: 148
as in title - in parent component I pass function as prop to child and I'd like to run this function inside child component, but in child's function.
//parent component
<div>
<Child myFunction={this.myFunction} />
</div>
and in child component I create new function
//child component
newFunction = () => {
//someNewCode
this.props.myFunction();
}
<button onClick={this.newFunction}>click me</button>
but it's not working. Where's the problem?
Upvotes: 1
Views: 51
Reputation: 12129
The following should work.
Perhaps this.myFunction
isn't an arrow function and you forgot to bind it.
class Parent extends React.Component {
myFunction = () => {
console.log("Luke, I am your father");
};
render() {
return <Child myFunction={this.myFunction} />;
}
}
class Child extends React.Component {
newFunction = () => {
this.props.myFunction();
}
render() {
return <button onClick={this.newFunction}>click me</button>;
}
}
ReactDOM.render(<Parent />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root'></div>
Upvotes: 4