6

I would like to press the Enter Key and send a message. I try this:

But there is an error.

<input type="text" className="form-control input-sm chat_input" placeholder="Write your message here..."
                        onChange={this.handleTextChange} value={this.state.newMessage}
                    />
<span className="input-group-btn">
<input type="submit" value="Send" className="btn btn-primary btn-sm" onSubmit={this.handleSendMessage}                       
                    /></span>

And I want to manage my function:

handleSendMessage = e => {}

I already try OnKeyPressed but I can't call my functions there. Thank you.

I prefer a solution without jquery

2 Answers 2

7

You would add a keyPress event on the input text input and then detect for an enter key press using e.which ===13

onKeyPress = (e) => {
    if(e.which === 13) {
      this.handleSendMessage();
    }
  }
  render() {
    return (
    <div style={styles}>
      <input type="text" className="form-control input-sm chat_input" placeholder="Write your message here..."
        onChange={this.handleTextChange} onKeyPress={this.onKeyPress} value={this.state.newMessage}
      />
      <span className="input-group-btn">
        <input type="submit" value="Send" className="btn btn-primary btn-sm" onSubmit={this.handleSendMessage}
        /></span>
  </div>
    );

}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use a form for it and change your button type to submit

<form onSubmit={this.handleSendMessage}>
  <input type="text" className="form-control input-sm chat_input"
    placeholder="Write your message here..."
    onChange={this.handleTextChange} value={this.state.newMessage}
  />
  <span className="input-group-btn">
    <input type="submit" value="Send" className="btn btn-primary btn-sm"/>
  </span>
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.