I just had the craziest bug. In my onKeyDown I destructred the preventDefault out of e. However when I would call preventDefault() I would get:
TypeError: this is undefined[Learn More]react-dom.js:13987:5
I am using React v15.4.1 and the line is highlighted in my screenshot below:

If I don't destructure and just use e.preventDefaut() it works. Does anyone know why this is? Is this a bug in babel?
const El = React.createClass({
displayName: 'El',
onKeyDown(e) {
let { key, preventDefault } = e;
preventDefault();
},
render() {
return React.createElement('input', { onKeyDown:this.onKeyDown });
}
});
Implementation of preventDefault method depends on other properties of event object, which are referred by this (namely: this.defaultPrevented property). When you destructure it from e, you detach this function from the base e object, which means that you loose context this. preventDefault method requires to be properly called with correct e object context. You can confirm this by calling it with event context which you can do with Function.prototype.call:
onKeyDown(e) {
let { key, preventDefault } = e;
preventDefault.call(e);
},
I would not destructure preventDefault.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With