Advertisement
deedspool

FormItem.tsx

Nov 27th, 2023
1,178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Form as AntdForm } from 'antd'
  2. import type React from 'react'
  3. import { useEffect } from 'react'
  4. import type { Control, FieldPath, FieldValues } from 'react-hook-form'
  5. import { useController } from 'react-hook-form'
  6.  
  7. type AntdFormItemProps = React.ComponentProps<typeof AntdForm.Item>
  8.  
  9. export type FormItemProps<TFieldValues extends FieldValues = FieldValues> = {
  10.   children: React.ReactNode
  11.   control: Control<TFieldValues>
  12.   name: FieldPath<TFieldValues>
  13. } & Omit<AntdFormItemProps, 'name' | 'normalize' | 'rules' | 'validateStatus'>
  14.  
  15. // TODO: Support `onBlur` `ref`
  16. // FIXME: `Touched` does not change in devtool
  17. export const FormItem = <TFieldValues extends FieldValues = FieldValues>({
  18.   children,
  19.   control,
  20.   name,
  21.   help,
  22.   ...props
  23. }: FormItemProps<TFieldValues>) => {
  24.   const { field, fieldState } = useController({ name, control })
  25.   const form = AntdForm.useFormInstance()
  26.  
  27.   const handleNormalize: AntdFormItemProps['normalize'] = (value) => {
  28.     field.onChange(value)
  29.     return value
  30.   }
  31.  
  32.   // watch field value here
  33.   useEffect(() => {
  34.     form.setFieldValue(name, field.value)
  35.   }, [form, name, field.value])
  36.  
  37.   return (
  38.     <AntdForm.Item
  39.       {...props}
  40.       name={name as string}
  41.       initialValue={field.value}
  42.       normalize={handleNormalize}
  43.       validateStatus={fieldState.invalid ? 'error' : undefined}
  44.       help={fieldState.error?.message ?? help}
  45.     >
  46.       {children}
  47.     </AntdForm.Item>
  48.   )
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement