10
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【React】 FormでEnterキーを押した時にSubmitされるのを防ぐ

Last updated at Posted at 2019-10-05

Reactで作成したForm内でEnterキーを押すと、勝手にSubmitされてしまい、画面がリロードされて困ったのでメモです。

Form.js
handleSubmit(e) {
    e.preventDefault();
  }

render() {
  return(
    <div className="search-item">
      <form
        className="search-item__form"
        onSubmit={e => this.handleSubmit(e)}
      >
        <input
          type="text"
          className="search-item__item-search-field"
        />
      </form>
    </div>
  )
}

HTMLではformタグの中にonSubmit="return false;"と記述すればSubmitされることはないのですがReactでは思うように動作しないため、
上記のようにe.preventDefault();を使うとエンターキーを押してもSubmitされるのを防ぐことができます。

10
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?