Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear multi select (react-select)

I use https://github.com/JedWatson/react-select.

My Component sample:
selectedOptions: [] In first load component multi select is empty. When i select some values I have values which i write to selectedOptions. In this case it works correctly. But when I clear selectedOptions view doesnt update.

There are example https://codesandbox.io/s/xovn7n2lz4

<Select
            defaultValue={selectedOptions}
            isMulti={isMulti}
            onChange={onChange}
            options={options}
            placeholder={placeholder}
            styles={colourStyles}
            theme={(theme) => ({
                ...theme,
                position: 'static',
                borderRadius: 0,
                colors: {
                    ...theme.colors,
                    primary25: darkTheme.colors.hoverColor,
                    primary: darkTheme.colors.hoverColor,
                    neutral0: normalElemColor,
                    neutral80: standardFontColor,
                },
                spacing: {
                    ...theme.spacing,
                    controlHeight: 24,
                    baseUnit: 1
                }
            })}
        />
like image 462
Lukashenko Yevhenii Avatar asked Dec 07 '18 09:12

Lukashenko Yevhenii


People also ask

How do you clear the selected value in React select?

You can clear the value of react select using the ref. Just store the value in the state, and change the state programmatically using componentDidUpdate etc... Note: 'value' should be an object. A simple option would be to pass null to the value prop.

How do I use onChange With React select?

To handle the onChange event on a select element in React: Set the onChange prop on the select element. Keep the value of the selected option in a state variable. Every time the user changes the selected option, update the state variable.


1 Answers

You are using uncontrolled input.

Change

 <Select isMulti
          defaultValue={selectedOptions}         
          onChange={this.onInputChange}
          name="color"
          options={colourOptions}
        />

To

<Select
          isMulti
          defaultValue={selectedOptions}
          value={selectedOptions}
          onChange={this.onInputChange}
          name="color"
          options={colourOptions}
        />

You have defined onchange but didn't provide any value. I suggest you to react controlled vs uncontrolled

demo

like image 126
Just code Avatar answered Sep 20 '22 16:09

Just code