Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js how to make a correct callback prop function? [duplicate]

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?

like image 257
Karlo A. López Avatar asked Jan 28 '26 05:01

Karlo A. López


2 Answers

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.

like image 171
jered Avatar answered Jan 29 '26 18:01

jered


You need to bind the showCirculares with the class so that it does not have this undefined. Following are the ways to do this.

Bind your method in constructor like this

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

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

Or simply use arrow function like this

showCirculares = () => {
   this.props.showView("circulares");
}
like image 32
Prakash Sharma Avatar answered Jan 29 '26 19:01

Prakash Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!