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

Drawer.Triggerの子要素に自作コンポーネントが使用できない【ChakraUI】

0
Posted at

現状

・ChakuraUIでメニューボタンを作成したい。
・Drawer.Triggerの子要素を別コンポーネントに分割したらメニューが開かなくなった。
・コンポーネントに書いている内容は全く同じ。

beforeCode1.tsx
<Drawer.Trigger asChild>
    <IconButton>
        <GiHamburgerMenu />
    </IconButton>
</Drawer.Trigger>

⬆️問題なく動く

beforeCode2.tsx
<Drawer.Trigger asChild>
    <MenuIconButton />
</Drawer.Trigger>

⬆️メニューをクリックしても反応がない。エラーも出ない。

原因

asChildにヒントが隠れていた。

asChildは自作コンポーネントにpropsを渡しているのだが、自作コンポーネントはそれをうまく子要素に引き継げていないようだ。
➡️onClickなどの指定がbuttonに届いていないため動かなかった

解決策

IconButtonにスプレッド構文でpropsを渡す
合わせてChakraUI v3ではasChildを使う際にrefの追加も推奨されている

改善コード

afterCode.tsx
type MenuButtonProps = IconButtonProps & {
  ref ?: React.Ref<HTMLButtonElement>;
}


export const MenuIconButton = ({ref, ...props}: MenuButtonProps)  => {

  return (
    <IconButton ref={ref} {...props}>
        <GiHamburgerMenu />
    </IconButton>
  )
}

このコードは何をしているのか

ref ?: React.Ref<HTMLButtonElement>;

  • buttonが参照できる型でRefを追加する
  • RefとはDOM要素への入り口
    例えばbuttonのonClickにアクセスできるようになるということらしい
    (初学者なので解釈が違うかもしれません)
  • 使用しているChakraUI v3のIconButtonPropsにはRefが含まれていなかったので今回は別で追加している
  • React v19には含まれているっぽい

参考

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