RebootGG
RebootGG

Reputation: 131

How to only send the value of selected option with react-select and react-hook-form

I'm trying to build a form with custom generic components, using RHF and react-select.

When I submit the form, I want the select to give me 'option-1', instead of { value: 'option-1', label: 'Option 1' }.

While it doesn't seem very complicated, I can't get it right and I keep getting confused around RHF Controller usage and Select props.

Because of the generic approach, I don't want to transform the data at the form level, and would like to keep the logic in the SelectField component.

Here is a codesandbox

Thank you for your help.

Upvotes: 1

Views: 2794

Answers (1)

justdvl
justdvl

Reputation: 874

Your options is array of label value object. So when you are setting the option, it will set it as selected object from this options array. If you want to store only the string in the userData that you are setting, than simply do:

            onChange: (item): void => onChange(item.value),

in your SelectField > SelectWrapper component

https://codesandbox.io/s/wizardly-moore-qsil7?file=/src/SelectField.tsx

Hope I got your request right.

Upvotes: 2

Related Questions