Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If destructure preventDefault - with babel in react - this is undefined

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 });
  }
});
like image 433
Noitidart Avatar asked Dec 09 '16 11:12

Noitidart


1 Answers

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.

like image 111
dfsq Avatar answered Nov 14 '22 07:11

dfsq