2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

chakra ui v2 コンポーネント化する際にカスタム以外のpropsも渡せるようにするには?

Posted at

はじめに

chakra ui v2の ButtonSaveButtonとしてコンポーネント化する際に、Button 自体のpropsもコンポーネント呼び出し先から指定できるようにしたかったので方法を調べた結果を共有します。

やり方

  • Button のprops型である ButtonProps をカスタムの型と&する
  • propsの分割代入先に ...rest としてカスタムのprops以外をまとめて受け取れるようにする
SaveButton.tsx
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Button, ButtonProps } from "@chakra-ui/react";
import React, { FC } from "react";

type Props = {
  text: string;
  onClick: () => void;
  iconType?:
    | React.ReactElement<unknown, string | React.JSXElementConstructor<any>>
    | undefined;
};
export const SaveButton: FC<Props & ButtonProps> = (props) => {
  const { text, onClick, iconType, ...rest } = props;
  return (
    <Button colorScheme="blue" rightIcon={iconType} onClick={onClick} {...rest}>
      {text}
    </Button>
  );
};


使い方の例

Button の元々のpropsである type="submit" を指定できるようになりました!

<SaveButton text="登録" onClick={onClickSaveTodo} type="submit" />

その他のpropsも、もちろん指定できます。

おわりに

今までは、元々のprops指定できなくない!?と思ってたけど、これで気兼ねなくコンポーネント化できる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?