サイト名変更・お引越しのお知らせ

【Chakra UI】TypeScriptでAlertDialogのleastDestructiveRefとrefでエラーが出る場合の対処法

Chakra UIのAlertDialogのドキュメントをそのまま使うと、The expected type comes from property 'leastDestructiveRef' which is declared here on type 'IntrinsicAttributes & AlertDialogProps'のようなエラーが表示されます。

モグモグさん

本記事は結論だけさくっと紹介します。

バージョン
  • @chakra-ui/react 2.4.9

対処法

useRefに型を渡すことで解決できます。

function AlertDialogExample() {
  const { isOpen, onOpen, onClose } = useDisclosure()
  // before
  // const cancelRef = React.useRef()
  // after
  const cancelRef = useRef<HTMLButtonElement>(null); // HTMLButtonElementを渡す

  return (
    <>
      <Button colorScheme='red' onClick={onOpen}>
        Delete Customer
      </Button>

      <AlertDialog
        isOpen={isOpen}
        leastDestructiveRef={cancelRef}
        onClose={onClose}
      >
        <AlertDialogOverlay>
          <AlertDialogContent>
            <AlertDialogHeader fontSize='lg' fontWeight='bold'>
              Delete Customer
            </AlertDialogHeader>

            <AlertDialogBody>
              Are you sure? You can't undo this action afterwards.
            </AlertDialogBody>

            <AlertDialogFooter>
              <Button ref={cancelRef} onClick={onClose}>
                Cancel
              </Button>
              <Button colorScheme='red' onClick={onClose} ml={3}>
                Delete
              </Button>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialogOverlay>
      </AlertDialog>
    </>
  )
}

useRefには中身に入りうるDOMノードを指定するので、このケースではHTMLButtonElementを渡してあげています。

まとめ

TypeScriptでChakra UIのAlertDialogのleastDestructiveRefとrefでエラーが出る場合の対処法を紹介しました。

TypeScriptでrefを使うときはよくあるので、仕組みを含めて理解しておけばOKだと思います。

useRefのドキュメントも置いておきます。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です