treycordova / nativejsx

JSX to native DOM API transpilation. :yellow_heart: <div> ⟹ document.createElement('div')!
MIT License
154 stars 14 forks source link

Can't use `this` in JSX #17

Closed odzb closed 7 years ago

odzb commented 7 years ago

If I want to use this in my JSX like this:

<div onMouseDown={this.handleMouseDown.bind(this)}>

Then it just won't work, because generated code gets enclosed in an IIFE which is not an arrow function.

treycordova commented 7 years ago

Alright, my solution to this problem is the following:

const element = <div onClick={this.onClick.bind(this)} />

Transpiles to

const element = function() {
  var $$a = document.createElement('div');
  $$a.addEventListener(this.onClick.bind(this));
  return $$a;
}.call(this);

I'd like to point out .call(this). That'll pipe through this anywhere JSX is used. It'll be up to the user to pipe it through larger expressions. That can be accomplished using arrow functions.

const element = (
  <ul>
    {[1, 2, 3].map(() => {
      return <li onClick={this.onClick.bind(this)} />
    }}
  </ul>
)
odzb commented 7 years ago

Looks good to me, thank you!

treycordova commented 7 years ago

Closing this up with the release of 4.0.0. Thanks again!