Reputation: 1030
I'm trying to pass a callback function from parent->child, but when the child component is rendered I get the error: TypeError: this.props.setCurrentWindow is not a function
.
Parent component where I am trying to pass the function setCurrentWindow
class Parent extends Component {
constructor(props){
super(props);
this.setCurrentWindow = this.setCurrentWindow.bind(this);
}
setCurrentWindow(){
console.log("called")
}
render(){
return(
<Child
setCurrentWindow={this.setCurrentWindow}
/>)}
}
child component where I am trying to call setCurrentWindow
class Child extends Component{
constructor(props){
super(props)
}
render(){
return(
<div
onClick={()=>{this.props.setCurrentWindow()}}>
{this.props.children}
</div>
)}
}
Why is setCurrentWindow
not being recognized as a function here?
Upvotes: 0
Views: 405
Reputation: 1030
A stupid answer but the final solution here is that not all instances of my child components were being passed this.setCurrentWindow hence the undefined error. Durrr! Thanks for the responses!
Upvotes: -1
Reputation: 12022
Try this:
parent.jsx:
class Parent extends Component {
// code omitted for brevity
handleSetWindow = () => {
//
};
render() {
return (
<div>
<Child onSetWindow={this.handleSetWindow}
/>
</div>
);
}
}
child.jsx:
class Child extends Component {
render() {
return (
<div>
<button onClick={() => this.props.onSetWindow()} >
Set
</button>
</div>
);
}
}
Upvotes: 1
Reputation: 5854
Please check this example where I only found the difference is to have child element like <div><h1>Hello</h1></div>
that was not in your code. other than this everything is working fine. When I click on the div, it writes called in console
export default class Parent extends Component {
constructor(props) {
super(props);
this.setCurrentWindow = this.setCurrentWindow.bind(this);
}
setCurrentWindow() {
console.log("called")
}
render() {
return (
<Child
setCurrentWindow={this.setCurrentWindow}
>
<div>
<h1>Hello</h1>
</div>
</Child>
)
}
}
class Child extends Component {
constructor(props) {
super(props)
}
render() {
return (
<div onClick={() => {
this.props.setCurrentWindow()
}}>
{this.props.children}
</div>
);
}
}
Upvotes: 1