LoginSignup
1
0

More than 1 year has passed since last update.

<button>などの要素が持つ属性をpropsの型に指定するには

Last updated at Posted at 2023-04-08

そんな時にはReact.ComponentProps型が使える

このように使うことが出来ます。

type Props = {
  text: string
} & ComponentPropsWithoutRef<'button'>

const Button: FC<Props> = ({ text, ...otherProps }) => {
  return (
    <button {...otherProps}>
      {text}
    </button>
  )
}

コンポーネントを使う側はbutton要素に存在する属性を書く事が出来ます。

<Button
  text='hello'
  name='world'
  disabled={false}
  onClick={handleClick}
/>

嬉しい事として、Buttonコンポーネントに使いたい属性が増えるたびにその属性を書く手間が不要という事があるかと思います。コンポーネントを使う側で属性を追加するだけで済むので個人的に使いやすいなと思っています。
下記のようにnamedisabledonClickを追加したいとなった時に下記のように追加せず、

type Props = {
  text: string
+ name: string
+ disabled: boolean
+ handleClick: () => void
}

- const Button: FC<Props> = ({ text }) => {
+ const Button: FC<Props> = ({ text, name, disabled, handleClick }) => {
  return (
-    <button>
+    <button name={name} disabled={disabled} onClick={() => handleClick()}>
      {text}
    </button>
  )
}

コンポーネントを使う側だけ属性を追加すれば良いようになります。

<Button
   text='Hello'
+  name='button'
+  disabled={false}
+  onClick={handleClick}
/>

余談

ComponentPropsWithoutRefrefを受け取らない型なので、refを指定したい場合は、ComponentPropsWithRefがあるのでこちらを使う事になります。

まとめ

buttonなどの要素が持つ属性をpropsで使うにはと思った時の参考の一つになれば嬉しいです。

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