Sisky
Sisky

Reputation: 603

Passing options with multiple values that are the same in to React-select

Below is a snippet of how I call the Select menu:

import Select from 'react-select';

const SelectMenu = (props) => {
  const { options, defaultValue, onChange, name, label } = props;
  return (  
      <Select
        options={options}
        defaultValue={defaultValue}
        onChange={onChange}
        name={name}
        id="search-select"
      />
  );
};

My options object looks as follows:

TestObj: [
  {
    label: 'Test 1',
    value: 3.49
  },
  {
    label: 'Test 2',
    value: 3.99
  },
  {
    label: 'Test 3',
    value: 3.89
  },
  {
    label: 'Test 4',
    value: 3.99
  },
  {
    label: 'Test 5',
    value: 0
  }
]

Because of the fact two of the options share the same value I get this effect:

enter image description here

As can be seen due to Test 2 and 4 sharing the same value they both show as selected.

Is there a way that whilst keeping the same values I can have this so that it only selects the actual selected option?

Upvotes: 3

Views: 3780

Answers (1)

noetix
noetix

Reputation: 4923

The way react-select by default checks if a value is selected is by extracting the value piece and comparing it to whats selected (an array of objects with a value key.)

Using isOptionSelected you can override the strategy employed:

isOptionSelected={(option, selectValue) => selectValue.some(i => i === option)}

This is more or less how the internal function works without extracting the value part, and instead compares the whole object.

Upvotes: 5

Related Questions