0

I am having an onKeyPress Listener to my input component. Currently onKeyListener prints something when the enter key is hit.

This is current code

onKeyPress={this.onHitEnter.bind(this)}/>

onHitEnter = (e) => {
        if (e.key === 'Enter') {
          console.log()
    }

Now I want to send some addition params to onHitEnter method. I tried to do it but it didn't work

This is what I tried

onKeyPress={this.onHitEnter.bind(this, item, item.id, item.index)}/>

onHitEnter = (e, item, id, index) => {
        if (e.key === 'Enter') {
          console.log("enter")
            console.log(id)
    }

How can I send those additional parameters to onHitEnter method?

EdG
  • 2,243
  • 6
  • 48
  • 103

2 Answers2

3

When you use bind with additional arguments it will put the additional arguments first and the event object last

function foo (a, b, event) {
   console.log(arguments) 
} 


document.querySelector("button").addEventListener("mousedown", foo.bind(this, "a", "b"))
<button>Foo</button>

so you would need to reorder your arguments

onHitEnter = (item, id, index, e)
epascarello
  • 204,599
  • 20
  • 195
  • 236
1

I would recommend binding your function elsewhere.

you could get the data you need by using this shorthand expression, since you're using es6:

onKeyPress={e => this.onHitEnter(e, item, item.id, item.index)}/>

the expression defines the arguments you want to pass during the event.

mhough
  • 86
  • 2