Why is the value of this
in an event handler's callback different when using React?
For instance, when adding an event handler to an element in JS, the value of this
in the callback function is always the element upon which the handler is placed (assuming arrow functions are not used for callbacks). So, we have this:
button.onclick = function(event) {
alert(this); // [object HTMLButtonElement]
}
However, if I do the same thing in React:
<button onClick={function() {
alert(this); // undefined
}
}>
</button>
... as you can see, this
refers to undefined
rather than the button element.
Could this be an implication of "JSX callbacks"? Is it just a React thing?