3

I have the following code in a component:

  deleteShare: function(e) {
    console.dir(e);
  },

  render: function() {
    createShare = function(share) {
      return (
        <span key={share} className='share'>
          {share}
          <a href="#" onClick={this.deleteShare}>x</a>
        </span>
      )
    }

    return (
      <div>
        <input type='hidden' name='shares' value={this.state.shares.join(',')} />

        <div className='ticket_shares'>
          {this.state.shares.map(createShare)}
          <input type='text' id='new_share' placeholder='Add an email' onKeyDown={this.addShare}/>
        </div>
      </div>
    )
  }

However, I'm finding that the onClick on a anchor in createShare doesn't appear to trigger, like it's not binding. There's no error or anything in the console.

I assume there's something funky going on with the way React is setting up bindings to the event, or some sort of context issue. How can I resolve this?

Neil Middleton
  • 22,105
  • 18
  • 80
  • 134

1 Answers1

2

In createShare this will be bound to window, as it is inside the function.

You could change createShare to a method on the component, and React will autobind it to the component, or bind it to what you expect with Function.prototype.bind

Another nice solution is ES6 arrow functions which bind this to the scope they are defined in, but that will take a bit of setup

WayneC
  • 5,569
  • 2
  • 32
  • 43