1
1

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 1 year has passed since last update.

Enterキー押下でForm内のButtonにonClickイベントが発生する

Posted at

経緯

Semantic UI ReactでFormをよく使うのですが、EnterキーでButtonのonClickイベントが発生して困ったので、記録用に。

サンプルコード
import React from 'react'
import { Form, Button } from 'semantic-ui-react'

const FormExample = () => (
  <Form>
    <Form.Group widths='equal'>
      <Form.Input label='First name'  />
      <Form.Input label='Middle Name' />
      <Form.Input label='Last Name' />
    </Form.Group>
    <Form.TextArea label="Note" />
    <Button icon="plus" onClick={() => console.log("Click!")} />
  </Form>
)

export default FormExample

対処法1:ButtonをFormの外に出す

サンプルコードみたいに一番下や一番上にある場合は出すのが簡単。

対処法1を適用すると...
import React from 'react'
import { Form, Button } from 'semantic-ui-react'

const Solution1 = () => (
  <>
    <Form>
      <Form.Group widths='equal'>
        <Form.Input label='First name'  />
        <Form.Input label='Middle Name' />
        <Form.Input label='Last Name' />
      </Form.Group>
      <Form.TextArea label="Note" />
    </Form>
    <Button icon="plus" onClick={() => console.log("Click!")} />
  </>
)

export default Solution1

対処法2:Formを使わない

Formを使わず、InputやDropdownを使用する方法。
ただ、<Form.Input /><Input />ではlabelの表示が異なるため、注意が必要です。

対処法2を適用すると...
import React from 'react'
import { Input, Form, TextArea, Button } from 'semantic-ui-react'

const Solution2 = () => (
  <>
    <Input label='First name'  />
    <Input label='Middle Name' />
    <Input label='Last Name' />
    <Form>
      <TextArea label="Note" />
    </Form>
    <Button icon="plus" onClick={() => console.log("Click!")} />
  </>
)

export default Solution2

対処法3:Buttonにtype="button"を指定する

こちらの記事を参考にしました。
これが一番良い解決方法かなと思います。

対処法3を適用すると...
import React from 'react'
import { Input, Form, TextArea, Button } from 'semantic-ui-react'

const Solution3 = () => (
  <Form>
    <Form.Group widths='equal'>
      <Form.Input label='First name'  />
      <Form.Input label='Middle Name' />
      <Form.Input label='Last Name' />
    </Form.Group>
    <Form.TextArea label="Note" />
    <Button icon="plus" onClick={() => console.log("Click!")} type="button" />
  </Form>
)

export default Solution3
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?