Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React missing an onClick? [duplicate]

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?

like image 447
Neil Middleton Avatar asked Mar 09 '26 00:03

Neil Middleton


1 Answers

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

like image 115
WayneC Avatar answered Mar 11 '26 14:03

WayneC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!