react-hook-forms not validating react-select control with a defaultValue

Viewed 414

I am working on a form using react-hook-form, I needed a searchable select so I created a component using react-select. My problem is, I am passing a default value on load and if I use trigger() to validate the field, I get an invalid on the <Select>.. this getValues() it pulls the correct value.. If I select a new value in the dropdown, it works.. just won't accept a default value..

I created a sandbox if anyone has time to take a look?

1 Answers

Put your default value in the defaultValues prop provided by react-hook-form instead:

const formMethod = useForm<Address>({
  defaultValues: {
    state: options.find(({ value }) => value === "OH")
  }
});

And remove the defaultValue prop in the Select component. react-hook-form can only validate your data if it's aware of the defaultValues. Passing the default value directly to the Select is the same as not passing anything at all since it's react-hook-form who control the validation logic:

<Select
  {...props}
  // defaultValue={options.find(({ value }) => value === props.state)}
/>

Live Demo

Codesandbox Demo

Related