はじめに
NextUIのコンポーネントを使用するとき、独自のプロパティを追加したくなることがありませんか?🥺
そんなとき、各コンポーネントのProps型を拡張する方法が便利です。
今回はButtonコンポーネントを例に説明します。
❌ 私がやってしまった間違った実装
import { Button as NextUIButton } from "@nextui-org/react";
// 独自のプロパティだけを定義
type ButtonProps = {
isProcessing?: boolean;
children: React.ReactNode;
};
// これだとNextUIのプロパティが使えない!
export const CustomButton = ({
isProcessing,
children,
}: ButtonProps) => {
return (
<NextUIButton
disabled={isProcessing}
>
{isProcessing ? "処理中..." : children}
</NextUIButton>
);
};
✅ 正しい実装例
import { Button as NextUIButton, ButtonProps as NextUIButtonProps } from "@nextui-org/react";
// コンポーネントのPropsを継承して独自のプロパティを追加
type CustomButtonProps = NextUIButtonProps & {
isProcessing?: boolean;
};
export const CustomButton = ({
isProcessing,
children,
...props
}: CustomButtonProps) => {
return (
<NextUIButton
{...props}
disabled={isProcessing || props.disabled}
>
{isProcessing ? "処理中..." : children}
</NextUIButton>
);
};
使用例
// NextUIの標準プロパティが使える!
<CustomButton
color="primary" // OK
size="sm" // OK
variant="flat" // OK
>
クリック
</CustomButton>
// 独自プロパティも使える!
<CustomButton
color="primary"
isProcessing={true}
>
送信
</CustomButton>
なぜProps拡張が便利なのか?
- NextUIが提供する標準のプロパティがそのまま使える
- 独自のプロパティを型安全に追加できる
他のコンポーネントでも同じように使える
この手法は、他のNextUIコンポーネントでも同様に適用できます。
import { InputProps as NextUIInputProps, ModalProps as NextUIModalProps, CardProps as NextUICardProps } from "@nextui-org/react"
// Input
type CustomInputProps = NextUIInputProps & {
customValidator?: (value: string) => boolean;
};
// Modal
type CustomModalProps = NextUIModalProps & {
showCloseButton?: boolean;
};
// Card
type CustomCardProps = NextUICardProps & {
isHighlighted?: boolean;
};
まとめ
NextUIのコンポーネントのPropsを継承することで、既存の機能を維持しながら、簡単に独自の拡張ができます。
独自のPropsだけを定義してしまうと、NextUIの便利なプロパティが使えなくなってしまうので注意が必要であることを身をもって体感しました...😣