简体   繁体   中英

How to remove pre-selected options when loading select control?

I am using react-select and pre-selecting options (from state) when it loads. Using multiple select true. When I click on Select box it still shows the options which are already showing up. how to remove those from options list?

this is my code:

  const options = []
    {
        deviceData ? deviceData.forEach((element, key) => {
            options.push({ value: element.id, label: element.area })
        }) : null;
    }

         <Select isMulti
                                        isSearchable
                                            value={defaultSelected}
                                            onChange={handleChange}
                                            options={options}
                                        />

            function handleChange(selectedOption) {
                setDefaultSelected(selectedOption)
            };

    async function getRooms(deviceIds) {
        ... // filterring logic to select multiple options load 
    ... filteredDevices.push({ value: index, label: devicesAll.area })
            setDefaultSelected(filteredDevices) // This loads pre-selected values to multi select box. 
    }

Updated: I noticed pre-selection only works (value={defaultSelected}) when i supply value as index. so I am passing below as "defaultSelected" value where value: number

may be because of this it does not filter the value from select when it loads? console.log(filteredDevices)

{ id: "5d25f9d2dc4aea7838b0aa9f" label: "Meeting room 2" value: 0 }

在此处输入图像描述

Let me know if you need anymore code to understand this problem. Thanks

If I understand your question, you're wanting "default values" (provided by defaultSelected ) to be pre-selected on first render, and you'd like these to be changeable by the user during subsequent interaction.

One way would be via the defaultValue prop which should do what you want:

<Select isMulti isSearchable
        defaultValue={defaultSelected} // <-- use defaultValue instead
        onChange={handleChange}
        options={options} />

So for example, doing something like this:

const values = [
  { id: "5d25f9d2dc4aea7838b0aa9f", label: "Meeting room 2", value: 0 },
  { id: "5d25f9d2dc4aea7838b11111", label: "Meeting room 1", value: 1 }
];

<Select
    defaultValue={[values[0]]}
    isMulti
    name="colors"
    options={values} />

Here's a working example showing the above in action

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM