3

I'm trying to use a react-select component inside of a form created using react-hook-form. I have followed the instructions from the react-hook-form website here, but when I submit the form the value from the select component is "" (the default value).

I know that the form is working in general because other values that are input with ref={register} work fine. It's just this one value that I'm using the Controller for. Am I missing a prop in the Select component or am I going wrong somewhere else?

I have a parent component where the form is defined:

<Form id="public-share-form" onSubmit={handleSubmit(onSubmit)}>
   <Controller
    as={<PublicShareNetworkSelect />}
    name="network"
    control={control}
    defaultValue=""
   />
</Form>

Then a child component for the react-select component used in the as prop of the Controller:

return (
   <Select
   closeMenuOnSelect={true}
   options={networks}
   noOptionsMessage={() => "No matching options"}
   defaultValue=""
   className="basic-single"
   classNamePrefix="select"
/>
);

1 Answer 1

1

I think you need to use Select directly like this:

<Controller
  as={
    <Select
      closeMenuOnSelect={true}
      options={networks}
      noOptionsMessage={() => "No matching options"}
      defaultValue=""
      className="basic-single"
      classNamePrefix="select"
    />
  }
  name="network"
  control={control}
  defaultValue=""
/>
Sign up to request clarification or add additional context in comments.

3 Comments

So essentially I can't have the Select be embedded in a child function component?
yep, not like your code, if you want to do so, I think you need to use forwardRef to pass the ref down to child component
Thanks...I just moved the Controller to the child component to keep everything clean and it works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.