-2

Have built a chat feature in React.js. It works but the page is reloaded when sending the message. Better to be able to send a chat when pressing the enter, but it should not be reloaded. How can the app works to send a message with enter without reloading.

<form>
  <input
    name="chat"
    type="text"
    placeholder="Enter message"
    value={this.state.chat}
    onChange={this.handleChange}
  />
  <button
    onClick={() => this.handleSend(chat)}
  >
    <span>Send</span>
  </button>
</form>

If I don't use <form />, it won't be reloaded. But it doesn't work to send a message when pressing the enter.

k10a
  • 947
  • 2
  • 11
  • 30
  • 2
    Default `type` of `button` is `submit`. You need to chose a different button type (`button`), or prevent the default event action from within you revent handler function. – CBroe Mar 23 '20 at 08:37
  • 1
    Does this answer your question? [Stop form refreshing page on submit](https://stackoverflow.com/questions/19454310/stop-form-refreshing-page-on-submit) – Agney Mar 23 '20 at 08:47

2 Answers2

1

You need to change the type of the button other than Submit .Or handle the default behavior as e.preventDefault()

Sagar Ghimire
  • 231
  • 4
  • 10
1

You have two options:

1.) Change the type of the button to button instead of the default submit.

2.) Use e.preventDefault() function after the form submits to prevent the default action which is to reload the page.

laviRZ
  • 316
  • 1
  • 3
  • 11