Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
135
rated 0 times [  141] [ 6]  / answers: 1 / hits: 18549  / 7 Years ago, wed, october 25, 2017, 12:00:00

Im working with a react.js app, and I remember that I was able to pass a callback function from a child to a parent with pops, the thing is I cant achieve to do this again (I'd like to keep it simple, without Flux libraries):



So my parent App:



class App extends Component {
constructor(props) {
super(props);
}

showViewAction(viewToShow){
console.log(viewToShow);
}

render() {
return (
<div>
<AppMenu showView={this.showViewAction}/>
</div>
);
}
}


And my child AppMenu:



class AppMenu extends Component{

constructor(props) {
super(props);
}

showCirculares(){
this.props.showView(circulares);
}

render(){

return(
<div>
<MenuButton onClick={this.showCirculares} buttonTitle=SomeOtherProp/>
</div>
);
}
}


Everything I try, I always get:




Cannot read property 'props' of undefined at showCirculares;




I know this will be resolved with a simple task, and that this is basic React.js stuff, its just that I cant find a solution for this!! What am I doing wrong?


More From » reactjs

 Answers
26

Looks like you need to bind the this context to your callback functions. Do so in the constructor function like so:



App



class App extends Component {
constructor(props) {
super(props);
this.showViewAction = this.showViewAction.bind(this);
}

showViewAction(viewToShow){
console.log(viewToShow);
}

render() {
return (
<div>
<AppMenu showView={this.showViewAction}/>
</div>
);
}
}


AppMenu



class AppMenu extends Component{

constructor(props) {
super(props);
this.showCirculares = this.showCirculares.bind(this);
}

showCirculares(){
this.props.showView(circulares);
}

render(){

return(
<div>
<MenuButton onClick={this.showCirculares} buttonTitle=SomeOtherProp/>
</div>
);
}
}


Why? The short version is that unless you bind this, when your functions run the value of this is undefined. What you want is the context of the component instead, so you have to manually bind the functions to it.


[#56116] Monday, October 23, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
travion

Total Points: 137
Total Questions: 96
Total Answers: 103

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
travion questions
Mon, Dec 16, 19, 00:00, 5 Years ago
Sat, Oct 19, 19, 00:00, 5 Years ago
Fri, Sep 20, 19, 00:00, 5 Years ago
Wed, Nov 14, 18, 00:00, 6 Years ago
Sun, Oct 28, 18, 00:00, 6 Years ago
;