😄

shadcnのform使用時のエラーCannot destructure propertyの解決方法

2024/05/01に公開

エラー文の全容

TypeError: Cannot destructure property 'getFieldState' of '(0 , react_hook_form__WEBPACK_IMPORTED_MODULE_4__.useFormContext)(...)' as it is null.

Source
src\components\ui\form.tsx (45:11) @ getFieldState

  43 |   const fieldContext = React.useContext(FormFieldContext)
  44 |   const itemContext = React.useContext(FormItemContext)
> 45 |   const { getFieldState, formState } = useFormContext()
     |           ^
  46 |
  47 |   const fieldState = getFieldState(fieldContext.name, formState)

解決方法

react-hook-formからFormをimportしてしまっていたのでそれを修正するだけ

+ import { Form } from "@/components/ui/form";//正解
- import { Form } from "react-hook-form";//間違い

参考

https://github.com/shadcn-ui/ui/issues/800#issuecomment-1717240139

Discussion