gpbaculio
gpbaculio

Reputation: 5968

how to pass default event argument and an argument in react?

This is the function I want to invoke in an input type:

_handleOnEnterPress = (e, receiverUserId) => {
     if (e.keyCode === 13) { // guess keycode 13 is enter?
       console.log("pressed enter. user id = ",receiverUserId)
     }
  };

and this is the input type I want to invoke when ENTER is pressed, I used onKeydown

<input className="popup-input" 
  onKeyDown={this._handleOnEnterPress(chatFriendPopPup.id)} 
  onChange={this._handleMessageTextChange} 
  type='text'
/>

when I press enter, it's not logging on the console. I used e(event) default arg so it can detect the keycode 13 (enter) but I guess the if fails? since the receiverUserId is on 2nd index, do I not have to pass e (event) arg on onKeyDown when the function is invoked?

Upvotes: 2

Views: 356

Answers (2)

Andrii Starusiev
Andrii Starusiev

Reputation: 7764

Have you tried onKeyDown={(e) => this._handleOnEnterPress(e, chatFriendPopPup.id)} ?

Upvotes: 1

canaan seaton
canaan seaton

Reputation: 6868

Try using an arrow function to catch the event and then pass that event object as well any argument you like to the handler method of your choosing.

handler(e, someInput) {
    // do something in here

    if (someInput === 'foo') console.log('bar');
}

render() {
    const someArg = 'foo';
    return (
        <button onClick={e => this.handler(e, someArg)}>Do something</button>
    )
}

Upvotes: 0

Related Questions