azz0r
azz0r

Reputation: 3311

Correct way to pass data in JSX clicks

First

<div tabIndex="0"
  onKeyPress={this.onHandleClick.bind(null, 'first')}
  onClick={this.onHandleClick.bind(null, 'first')}>

Second

onHandleClick = (event) => {
  $(event.currentTarget).data('circle')
}
<div tabIndex="0"
  data-circle="first"
  onClick={this.onHandleClick}>

Is there another way to do this thats cleaner and the right way? Both of these feel like hacks: Especially using bind within the JSX.

Upvotes: 3

Views: 89

Answers (2)

Mat Zero
Mat Zero

Reputation: 386

Another situation that you may encounter yourself is needing the correct "this" pointer inside your callback, some arbitrary parameters and the event object itself. In that case you can do something like this:

<button onClick={(event) => this.handleAction('arbitrary-data', event)}> ... </button>

handleAction(data, event) {
  event.preventDefault()
  // this.state.something
  console.log(`data ${data}`)
}

Upvotes: 1

ZekeDroid
ZekeDroid

Reputation: 7209

If what you want is to pass parameters to your onClick handler, simply call it normally and have the function return a function:

onClick={this.onHandleClick('first')}

onHandleClick(value) {
    return function() {
        // logic that now has access to `value`
    }
}

Works just as well as binding, might be a little more clear. Definitely better than depending on jquery.

Upvotes: 3

Related Questions