-1

Have a look at the following code:

class App extends React.Component {


  go(){
    console.log("Hello",this);
  }
  render() {
    console.log("Hey",this);

    return ( 
      <button onClick={this.go}>Add profile</button>
    );
  } 
}

Why the value of this inside go is undefined? this inside render is an App instance and since we call this.go the value of this inside method go should be equal to the same App instance.

Unknown developer
  • 5,414
  • 13
  • 52
  • 100

1 Answers1

2

You need to bind go or use arrow function:

export default class App extends React.Component {
  go = () => {
    console.log('Hello', this);
  };
  render() {
    console.log('Hey', this);

    return <button onClick={this.go}>Add profile</button>;
  }
}
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118