33
22

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 Event + TypeScript

Last updated at Posted at 2019-08-12

ReactSynthetic Eventの型についてぐぐってばかりいるのでメモを残しておきます。

Synthetic Event とは?

onChange={event => console.log(event)}eventです。

SyntheticEvent – React

Synthetic Event の型

FormEvent

submit.tsx
import { FormEvent } from 'react';
...
const handleSubmit = (e: FormEvent) => {
...
<form onSubmit={handleSubmit}>
...
<button type="submit" onClick={handleSubmit}>Submit</button>
...

ChangeEvent

change.tsx
import { ChangeEvent } from 'react';
...
const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
...
const handleSelectChange = (e: ChangeEvent<HTMLSelectElement>) => {
...
<input value={inputValue} onChange={handleInputChange} type="text" />
...
<select value={selectValue} onChange={handleSelectChange}>
...

KeyboardEvent

keyPress.tsx
import { KeyboardEvent } from 'react';
...
const handleKeyPress = (e: KeyboardEvent) => {
...
const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
...
<textarea
  onKeyPress={handleKeyPress}
  onChange={handleChange}
...

MouseEvent

<HTML...Element>なしでdatasetを参照しようとするとタイプエラーがでます。
<button></button>以外にonClickをつけることを想定するなら<HTMLElement>を使ってしまうと楽です。

click.tsx
import { MouseEvent } from 'react';
...
const handleClick = (
  e: MouseEvent<HTMLButtonElement>
) => {
 e.preventDefault();
 console.log(e.currentTarget.dataset.id);
}
...
<button data-id={someId} onClick={handleClick}>click</button>
...
33
22
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
33
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?