Reactの関数コンポーネントをTypeScriptで作成する
Reactの関数コンポーネント(ファンクショナルコンポーネント)をTypeScriptで作成する方法を紹介します。
使用する型
よく使用する関数コンポーネントの型はFCとVFCです。
childrenをパラメータとして持つかどうかの違いがあり、FCはchilrenのパラメータを持ち、VFCは持ちません。
実際には以下のような使い方になります。
FC(childrenあり)<MyComponent>
子要素(children)
</MyComponent>VFC(childrenなし)<MyComponent />独自に作成するコンポーネントはVFCコンポーネントが多くなるかと思います。
VFCコンポーネント
以下はVFCの型を指定して、送信ボタンのコンポーネントを作成しています。
プロパティについてはReact 関数コンポーネントにプロパティを設定するで詳しく紹介しています。
SubmitButton.tsximport { VFC } from 'react';
type Props = {
isSubmitting?: boolean;
};
const SubmitButton: VFC<Props> = ({ isSubmitting }) => {
return (
<button disabled={isSubmitting}>
送信
</button>
);
};
export default SubmitButton;以下のように使用します。
使う側import SubmitButton from './SubmitButton';
<SubmitButton isSubmitting={isSubmitting} />FCコンポーネント
以下はFCの型を指定して、コンポーネントを作成しています。(このコンポーネントはreact-router-dom ログイン認証の仕組みを実装するで紹介したものです)
FCコンポーネントの場合はパラメータにchildrenを受け取ることができます。
AuthenticatedGuard.tsximport { useAuth } from './store/auth';
import { FC } from 'react';
import { Redirect, useLocation } from 'react-router-dom';
const AuthenticatedGuard: FC = ({ children }) => {
const { isAuthenticated } = useAuth();
const location = useLocation();
return isAuthenticated ? <>{children}</> : <Redirect to={{
pathname: '/login',
state: { from: location },
}} />;
};
export default AuthenticatedGuard;以下のように使用します。
使う側import AuthenticatedGuard from './AuthenticatedGuard';
<AuthenticatedGuard>
<AuthenticatedRoute />
</AuthenticatedGuard>