0

How do you set the value with javascript of a react-select component with grouped options? Grouped options as in this post.

Edit in reply to comment by @Tholle

I did not mention that I'm using Typescript, because questions tend to get less answers I think.

This is how I'm using the component:

<Select
    value={this.state.Industry}
    options={this.industryOptions}
    onChange={ (e) => this.handleChange("industry", e)}
></Select>

Where industryOptions is of this type:

industryOptions: Array<{label: string, options: Array<{label: string, value: string}>}>

E.g:

label: "Automotive"
options: Array(3)
    0: {label: "Car brand", value: "77"}
    1: {label: "Car dealer", value: "76"}
    2: {label: "Other", value: "75"}

When selecting an option in the dropdown this.state.Industry changes, but nothing happens with the Select component when this.state.Industry is changed.

burktelefon
  • 988
  • 2
  • 8
  • 27

1 Answers1

0

I'm answering my own question for future reference. I realized "value" should be of the same type as an option. I.e. an object of this type {label: string, value: string}, not a string. So I figuered I needed to search for an option that had the same value. This is in the render function of my component (parent of Select):

let indystryValue: {value: string, label: string}
let prospect: {value: string, label: string} | undefined;
this.industryOptions.forEach((io) => {
    prospect = io.options.find((o) => o.value == this.state!.measurementBasics!.Industry.toString());
    if(prospect !== undefined){
        indystryValue = prospect;
    }
});

...and put that in the Select like this:

<Select value={indystryValue!} ...

Although I got this compile error it is working: [ts] Type '{ value: string; label: string; }' is not assignable to type 'ValueType<{ label: string; options: { label: string; value: string; }[]; }>'. Type '{ value: string; label: string; }' is not assignable to type '{ label: string; options: { label: string; value: string; }[]; }[]'. Property 'length' is missing in type '{ value: string; label: string; }'. [2322] Select.d.ts(202, 3): The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes> & Readonly<{ children?: ReactNode; }> & Readonly>' (JSX attribute) value?: ValueType<{ label: string; options: { label: string; value: string; }[]; }>

burktelefon
  • 988
  • 2
  • 8
  • 27