1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

NextUIコンポーネントのProps拡張テクニック

Posted at

はじめに

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拡張が便利なのか?

  1. NextUIが提供する標準のプロパティがそのまま使える
  2. 独自のプロパティを型安全に追加できる

他のコンポーネントでも同じように使える

この手法は、他の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の便利なプロパティが使えなくなってしまうので注意が必要であることを身をもって体感しました...😣

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?