React Pass function to child component
If you can bind this function like this it will works
class Parent extends Component {
passedFunction = () => {};
render() {
<Child passedFunction={this.passedFunction} />;
}
}
class Child extends Component {
render() {
<div onClick={this.props.passedFunction} />;
}
}
Instead of having to bind your function in the constructor of the parent Class, you can use an arrow function to define your method so it is lexically bound using an arrow function
class Child extends Component {
render() {
<div onClick={this.props.passedFunction}></div>
}
}
class Parent extends Component {
passedFunction = () => {}
render() {
<Child passedFunction={this.passedFunction}/>
}
}
To Account for older version support of Javascript:
class Child extends Component {
render() {
<div onClick={this.props.passedFunction}></div>
}
}
class Parent extends Component {
constructor() {
this.passedFunction = this.passedFunction.bind(this)
}
passedFunction() {}
render() {
<Child passedFunction={this.passedFunction}/>
}
}
You are missing bind on the Child component.
this.props.passedFunction.bind(this)