6

Here is a snippet from my react js app:

<form className="rcw-sender" onKeyDown={(e)=> e.keyCode == 13 ? {sendMessage}: ''} onSubmit={sendMessage}>
  {this.state.active && <Container>
    <EmojiPicker />
  </Container>}
  <button className="rcw-send" onClick={activateEmoji}>
    <img src={emojibutton} className="rcw-send-icon" alt="send" />
  </button>
  <button className="rcw-send" onClick={activateMenu}>
    <img src={menubutton} className="rcw-send-icon" alt="send" />
  </button>

  <input type="text" className="rcw-new-message" name="message" placeholder={placeholder} disabled={disabledInput}
    autoFocus={autofocus} autoComplete="off" ref={this.input} />
  <button type="submit" className="rcw-send">
    <img src={send} className="rcw-send-icon" alt="send" />
  </button>
</form>

In my form onSubmit={sendMessage} is called when I press the submit button and this much works perfectly. But I want the same sendMessage to be invoked when I submit the form by pressing enter key. To do this I have this code onKeyDown={(e)=> e.keyCode == 13 ? {sendMessage}: ''} from which I want the sendMessage method to be invoked on pressing the enter key but it doesn't seem to work. I want to do this because I have an emoji picker in my app and when I submit the form using enter key in that case the emoji picker show's up. So to fix this I want to invoke the sendMessage method when I press the enter key to submit the form. Submitting the form using the submit button doesn't toggle the state of the emoji picker. That's why as a quick fix to the problem I want to invoke sendMessage method when I press enter key. How do I do it?

Venkat.R
  • 7,420
  • 5
  • 42
  • 63
node_man
  • 1,359
  • 4
  • 23
  • 50
  • 1
    share the sendMessage function code. i gues you would have added e.preventDefault() – Venkat.R Jul 21 '19 at 14:22
  • 2
    The problem is that you are not calling sendMessage when enter key is press. Just change it to sendMessage() – F.bernal Jul 21 '19 at 14:29
  • Possible duplicate of [How to handle the \`onKeyPress\` event in ReactJS?](https://stackoverflow.com/questions/27827234/how-to-handle-the-onkeypress-event-in-reactjs) – ravibagul91 Jul 21 '19 at 14:33
  • The default for [HTML button](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button) is `type="submit"`, pressing Enter in a text input triggers `submit` event and the first button's `onClick` handler might be called because of that... Does the problem persist if you add explicit `type="button"` to the first 2 buttons? – Aprillion Jul 21 '19 at 14:40
  • FTR `e.key === "Enter"` is more readable and [not deprecated like e.keyCode](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode) – Aprillion Jul 21 '19 at 14:42

4 Answers4

12

Try to move your onKeyDownHandler to separate function and just add if statement

  onKeyDownHandler = e => {
    if (e.keyCode === 13) {
      this.sendMessage();
    }
  };

  render() {
    ... your other code
    return (
      <form
        className="rcw-sender"
        onKeyDown={this.onKeyDownHandler}
        onSubmit={sendMessage}
      >
        {this.state.active && (
          <Container>
            <EmojiPicker />
          </Container>
        )}
        <button className="rcw-send" onClick={activateEmoji}>
          <img src={emojibutton} className="rcw-send-icon" alt="send" />
        </button>
        <button className="rcw-send" onClick={activateMenu}>
          <img src={menubutton} className="rcw-send-icon" alt="send" />
        </button>

        <input
          type="text"
          className="rcw-new-message"
          name="message"
          placeholder={placeholder}
          disabled={disabledInput}
          autoFocus={autofocus}
          autoComplete="off"
          ref={this.input}
        />
        <button type="submit" className="rcw-send">
          <img src={send} className="rcw-send-icon" alt="send" />
        </button>
      </form>
    );
  }
  • my sendMessage is defined like this Sender.propTypes = {sendMessage: PropTypes.func}; due to this I get an error this.sendMessage is not a function. I'm new to reactjs so I'm sorry if I missed out on something in the question – node_man Jul 21 '19 at 14:27
  • @no So just use this.props.sendMessage() – Stepan Vanzuriak Jul 21 '19 at 14:28
  • this works but another issue crops up. wait let me mention it here – node_man Jul 21 '19 at 14:56
  • when sendMessage is invoked by pressing enter key/or submit button the control goes to this code : handleMessageSubmit = (event) => {const userInpu =event.target.message.value;} . When submitted by pressing enter key I get cannot read property value of undefined. works perfectly when submitted by pressing submit button. – node_man Jul 21 '19 at 15:00
  • doing it like const userInpu = event.target.value; works perfectly when enter key is pressed but then gives error when submitted using submit button – node_man Jul 21 '19 at 15:07
  • @node_man Not sure I fully understand a new issue, maybe you should create another question – Stepan Vanzuriak Jul 21 '19 at 15:10
1

(e)=> e.keyCode == 13 ? {sendMessage}: ''

So what that function does? It takes a parameter named e, and then if e.keyCode == 13 it returns an object { sendMessage } (which is sugar for { sendMessage: sendMessage }), otherwise it returns an empty string.

Based on your intent, I think you wanted to write something like this:

(e) => {
  if (e.keyCode === 13)
    sendMessage();
}

or, as a one-liner (e) => e.keyCode === 13 && sendMessage().

dnt
  • 113
  • 1
  • 5
1

your input should have attribute onKeyPress

 onKeyPressHandler = e => {
     e.preventDefault();
     if (e.key === 'Enter') {
       // do something
     }
 };

 <input onKeyPress={this.onKeyPressHandler}/>
Nemer
  • 667
  • 1
  • 6
  • 10
-1
onKeyDown={e => {
    if (e.keyCode === 13) {
        this.sendMessage();
        e.preventDefault();
        e.stopPropagation();
    }
}}

preventDefault would be needed to prevent default action.

TopW3
  • 1,477
  • 1
  • 8
  • 14