Next.js + TypeScript でコンポーネントを書くとき、React.
から始まる型はとてもよく登場します。
しかし「どの型をどの場面で使うのか」が分からず、毎回調べてしまう…という人も多いはず。この記事ではNext.jsコンポーネントでよく使うReact型トップ10を用途別にまとめました。
📌 使用ツール
- Next.js
- TypeScript
- React
📌 特徴
- これらはすべてTypeScript専用の型
- 実行時には存在せず、ビルド時に型チェックだけして消える
-
Next.js
ではprops定義 / イベント定義 / 型再利用でよく使う
1)React.ReactNode
用途 : children
や柔軟に描画できる中身を受け取るとき。
type Props = {
children: React.ReactNode;
};
export default function Layout({ children }: Props) {
return <main>{children}</main>;
}
2)React.JSX.Element
用途 : 関数コンポーネントの戻り値型。
- 1つの要素 を返すことが確定している場合に使う。
const Page = (): React.JSX.Element => {
return <div>Hello World</div>;
};
3)React.FC
用途 : 関数コンポーネントの型。
- React 18 以降、
children
が削除されましたため、ご注意ください
const Card: React.FC<{ title: string }> = ({ title, children }) => (
<div>
<h2>{title}</h2>
</div>
);
4)React.ComponentProps
用途 : 既存コンポーネントやHTMLタグのprops型を取得。
type ButtonProps = React.ComponentProps<"button">;
const MyButton = (props: ButtonProps) => <button {...props} />;
5)React.ComponentPropsWithoutRef
用途 : ref を除いたprops型を取得(再利用しやすい)。
type InputProps = React.ComponentPropsWithoutRef<"input">;
const MyInput = (props: InputProps) => <input {...props} />;
6)React.ComponentPropsWithRef
用途 : ref を含むprops型を取得。
type InputWithRefProps = React.ComponentPropsWithRef<"input">;
const InputWithRef = React.forwardRef<HTMLInputElement, InputWithRefProps>(
(props, ref) => <input ref={ref} {...props} />
);
7)React.MouseEvent<T>
用途 : クリックなどマウスイベントの型。
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
console.log(e.currentTarget);
};
<T>
には下記などが入ります。
-
<HTMLButtonElement>
→<button>
のクリックイベント -
<HTMLDivElement>
→<div>
のクリックイベント -
<HTMLAnchorElement>
→<a>
のクリックイベント(リンク) -
<HTMLSpanElement>
→<span>
のクリックイベント -
<HTMLImageElement>
→<img>
のクリックイベント
8)React.ChangeEvent<T>
用途 : フォーム入力の変更イベント型。
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log(e.target.value);
};
<T>
には下記などが入ります。
-
<HTMLInputElement>
→<input>
の change イベント -
<HTMLTextAreaElement>
→<textarea>
の change イベント -
<HTMLSelectElement>
→<select>
の change イベント
9)React.FormEvent
用途 : フォーム送信や値変更など、フォーム全体のイベント型。
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
console.log("送信");
};
10)React.KeyboardEvent
用途 : キーボード操作のイベント型。
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
console.log("Enterが押された");
}
};
📌 まとめ
-
props型
→React.ReactNode
/React.ComponentProps
系 -
戻り値型
→React.JSX.Element
-
イベント型
→React.MouseEvent
/React.ChangeEvent
/React.FormEvent
/React.KeyboardEvent