jsun969 / react-hook-form-antd

๐Ÿ“‹๐Ÿœ Master your Ant Design form with React Hook Form! ็”จ React Hook Form ๆ‹ฟๆไฝ ็š„ Ant Design ่กจๅ•๏ผ
https://npm.im/react-hook-form-antd
MIT License
61 stars 10 forks source link

The onChange of the antd inputs does not work inside the FormItem #73

Closed avegatolber closed 9 months ago

avegatolber commented 9 months ago

Codesandbox here

jsun969 commented 9 months ago

I assume you should try watch in react hook form instead of onChange. Docs here

avegatolber commented 9 months ago

It seems that the useController field is overwriting the onChange of the antd input in FormItem.tsx

jsun969 commented 9 months ago

Yea. Also it's not recommended to use onChange or value with react-hook-form. Check the react hook form's documentation first then use this lib plz.

avegatolber commented 9 months ago

I understand but sometimes it is necessary, especially in ANTD Select components, where in the second parameter of the onChange you receive the option with all the information of the selected element, including the id, label and anything else. That is exactly why I need to use the onChange but it is not working.

And the "onChange" through the watch does not give me this information.

I understand that it is not recommended to use, but in this case it does not even give me the option to use it because it does not work. However in the demo it is working, it must have been some versioning issue i guess.

I will see what alternative I can find, thanks anyway

avegatolber commented 9 months ago

Adding this code to FormItem children solved my problem. It's probably not the best way to do it, but it works for me. Now i can access to the options from the onChange event in the Antd Select component and the form still working as expected.

{Children.map(
   children,
      (child) =>
         isValidElement(child) &&
         cloneElement(child, {
           ...field,
           //@ts-expect-error onChange type safe is not necessary here
           onChange: (...params) => {
              child.props.onChange && child.props.onChange(...params)
              field.onChange(...params)
             },
            onBlur: () => {
              child.props.onBlur && child.props.onBlur()
              field.onBlur()
            },
            ...(valuePropName && {
            [valuePropName]: field.value,
       }),
   }),
)}
jsun969 commented 9 months ago

Sounds reasonable. Could you help create a PR for your awesome idea? Thank you so much!

avegatolber commented 9 months ago

PR

Is my first time contributing, I hope I did the PR well ๐Ÿ˜„.

jsun969 commented 9 months ago

@avegatolber thx a lot for the PR. There are some minor fixes I need to deal with. I'll publish your feature ASAP!