Search code examples
reactjsreact-hook-formreact-forwardref

forwardRef on Select does not save chosen value with react-hook-form


I am building a library of react components.

This text field works by passing a ref with forwardRef:

export const TextField = React.forwardRef((props:TextFieldProps, ref) => {

return (
    <input ref={ref}....

However when I try the same with a select:

export const SimpleSelect = React.forwardRef((props: SimpleSelectProps, ref: Ref<HTMLSelectElement>) => {

const options = props.options

return (
  <select ref={ref}  className="Select">
    <option>-- Select an option --</option>
    {options &&
      options.map((option: OptionsType) => (
        <option key={option.value} value={option.value}>
          {option.label}
        </option>

And then I use in my own app like this:

<form onSubmit={handleSubmit(onSubmit)}>
  <SimpleSelect
    {...register('thingId', { required: true })}
    title="Thing"
    options={
      things &&
      things.map(({ thing }: Thing) => ({
        value: thing.uid,
        label: thing.primaryName,
      }))
    }
  />

The selected option does not save, and I can see this as when I submit the form, it tries to submit "-- Select an option --" even after choosing an option.


Solution

  • You need to spread the props provided by RHF in the select component to make your control works properly. Specifically, the select needs a name attribute so it can be identified and onChange so RHF can listen to the option changed event:

    <select ref={ref} className="Select" {...props}>
    

    Codesandbox Demo