2

class Foo extends React.Component{
  constructor( props ){
    super( props );
  }
 
  handleClick(event){
    console.log(this); // 'this' is undefined
  }
 
  render(){
    return (
      <button type="button" onClick={this.handleClick}>
        Click Me
      </button>
    );
  }
}
 
ReactDOM.render(
  <Foo />,
  document.getElementById("app")
);

I've red about this keyword, but i can't understand why in this case when i click on the button this is undefined? In this case this should point to the class Foo , why it is windows object? How the context is lost in this case?

  • Looks like react is binding the `window` object on onClick and check it what you get if you explicitly bind `this.handleClick.bind(this)` – Muhammad Nov 17 '19 at 19:52

1 Answers1

0
handleClick = (event)=>{
    console.log(this); //
  }

This is due to context use arrow function

handleClick is call in the context of click event of button, due to this refers to window context in handleClick, but when you use arrow function it will solve the issue

Saurabh Yadav
  • 3,303
  • 1
  • 10
  • 20
  • I've red about this keyword, but i can't understand why in this case when i click on the button this is undefined? In this case this should point to the class Foo , why it is windows object? How the context is lost in this case? –  Nov 17 '19 at 19:20
  • because onClick callback is called in the global context and global context is window in this case. – Saurabh Yadav Nov 17 '19 at 19:22
  • this rule is valid for all methods inside classes? we should bind all methods inside class components? –  Nov 17 '19 at 19:27
  • we should bind all methods inside class components? - NO - only when current execution context change means in your case - the handleClick function is called in the context of onClick – Saurabh Yadav Nov 17 '19 at 19:30
  • When the code is called from an inline on-event handler, its this is set to the DOM element on which the listener is placed, now in onClick the inner function's this isn't set so it returns the global/window object (i.e. the default object in non–strict mode where this isn't set by the call). – Saurabh Yadav Nov 17 '19 at 19:34