Search code examples
reactjsreact-hook-formreact-select

Using React Hook Forms with React Select: Cannot get onChange to trigger on form


We're in the process of rewriting our frontend using new tools. Part of this is React Hook form. Our old frontend updated whenever you made a change, so in order to provide a similar user experience, we want to do the same for the new frontend. We're therefor triggering form submission every time the form is updated. I realise this is not the default approach for React Hook form. Whether this means it's a bad idea altogether, i don't know yet.

We've built the majority of a page and so far everything has been working fine while using standard html inputs and selects. We've just tried implementing a multiple select using React-select, which gave us an issue with the onChange on the form never triggering.

I've made a barebone example here: https://codesandbox.io/p/sandbox/react-select-and-react-hook-form-forked-2v75xv

It has two Controlled selects. One with standard and one using react-select. Making a change in the one with standard html, triggers the onChange as can be seen in the console by the console log. Making changes in the react-select does not.

We've discovered that the change is actually being registered by react hook form, but the onChange event is just not being fired. We've seen this by making changes to the react-select and then modifying another field using standard html, which triggers the submit and we can then see that data is actually updated. To summarise:

  1. Changes made in default html triggers form onChange
  2. Changes made in react-select does not trigger form onChange
  3. Changes made in both default html and react-select is registered in formState

My goal is to get react-select to trigger onChange, so that it works similarly to the rest of the fields we already have. I'm thinking that this could be related to event propagation, and specifically the prevention of this, but I dont know how to verify this.

Ultimately my question is: How can i get changes made in the react-select to trigger the form onChange?


Solution

  • At least in your codesandbox, it appears you are running v6 of react-hook-form but you are using it like it's v7. The API of render on Controller changed in v7, and you are consuming this. However, the included version on the sandbox is v6. This has the effect that ...field is actually completely empty.

    Updating it in the sandbox fixes the issue.

    If you are wondering how the plain <select> worked at all, that's because you are using the native browser onChange attribute on <form> which detects changes to native controls.

    That is possibly problematic in future for any control that doesn't use a native control under the hood. You should achieve the submit on change thing differently: https://stackoverflow.com/a/70119332/1086398.