react-select : the option `isSelected` is always true

Viewed 1479

when nothing is selected

when nothing is selected

It works perfectly fine, when nothing is selected.

when one option is selected (problem)

when selected

As you see above, even if I selected one option(ash), it said everything was selected. I did console.log(isSelected), and it said everything was selected true ..

It should be like this...

react-select selected props

I copied a lot of code, few lines were modified.

here's my code

thank you in advance for helping me!

if you have any suggestion, please hit me!

const dot = (color = '#ccc') => ({
  display: 'flex',
  alignItems: 'center',

  ':before': {
    backgroundColor: color,
    borderRadius: 10,
    content: '" "',
    display: 'block',
    marginRight: 10,
    height: 15,
    width: 15,
  },
});

const colourStyles = {
  control: (styles, { selectProps: { width } }) => ({
    ...styles,
    width: width,
  }),
  option: (styles, { data, isSelected, isFocused }) => {
    const color = chroma(data.color);
    return {
      ...styles,
      backgroundColor: isSelected
        ? data.color
        : isFocused
        ? color.alpha(0.1).css()
        : null,
      color: isSelected
        ? chroma.contrast(color, 'white') > 2
          ? 'white'
          : 'black'
        : data.color,
    };
  },
  input: (styles) => ({ ...styles, ...dot() }),
  placeholder: (styles) => ({ ...styles, ...dot() }),
  singleValue: (styles, { data }) => ({ ...styles, ...dot(data.color) }),
};


const SelectModule = observer(({ label, value }) => {
  const [selectedOption, setSelectedOption] = useState('');

  const options = colorChipListStore.colorList.map((item) => ({
    color: item.hexId,
    label: item.label,
  }));


  const setColors = (color) => {
    setSelectedOption(color);
  };

  function customTheme(theme) {
    return {
      ...theme,
      colors: {
        ...theme.colors,
        primary: '#AD9EE5',
      },
    };
  }


return (
    <Container>
      {label && <Label>{label}</Label>}
      <OptionWrapper>
          <Select
            width='100%'
            options={options}
            styles={colourStyles}
            theme={customTheme}
            isSearchable
            onChange={setColors}
            defaultValue={selectedOption}
          />
      </OptionWrapper>
    </Container>
  );
});
1 Answers

Your options object does not have a value key. I was also getting this but when I changed my options to the format: options = [{label: '', value: ''}] I was able to get the correct option selected. The default behavior is to use the key of 'value' for the selected option check. You can change this behavior by using 'isOptionSelected' and resetting the option to whichever key you would like to use as your check. You can also add values to your object.

See this GitHub issue.

Related