I want to use grouped options. I want to get group of selected value. For example when I selected green, how can I know it is a color?
sandbox: https://codesandbox.io/s/codesandboxer-example-forked-x3l2c4?file=/example.tsx
Color --> red, yellow, green
Flavor --> Vanilla, Chocolate
import React, { Fragment } from 'react';
import Select, { components, MenuProps } from 'react-select';
import {
ColourOption,
colourOptions,
FlavourOption,
GroupedOption,
groupedOptions,
} from './docs/data';
function onChangeHandler(val){
console.log("val:" ,val)
}
export default () => (
<Select<ColourOption | FlavourOption, false, GroupedOption>
defaultValue={colourOptions[1]}
options={groupedOptions}
onChange={onChangeHandler}
/>
);
If I understood you correctly you want to know about all selected options and at the same time you also want to know which option belongs to which group.
You can not do this by default, however you can customize your group options and
add another key which can indicate group reference/name so this way when onChange
callback will be triggered you will get that option and you can see your group reference/name.
Check out this example and live-demo here.
import React from "react";
import Select from "react-select";
import {
ColourOption,
FlavourOption,
GroupedOption,
groupedOptions
} from "./docs/data";
function onChangeHandler(val, meta) {
console.log(val, "val");
const selectedOptions = val;
let goupedSelected = new Map();
selectedOptions.forEach((option) => {
const { groupName: key } = option;
const found = goupedSelected.get(key);
if (found) {
found.options = [...found.options, option];
} else {
goupedSelected.set(key, {
groupName: key,
options: [option]
});
}
});
console.log([...goupedSelected.values()]);
}
export default () => (
<Select<ColourOption | FlavourOption, true, GroupedOption>
options={groupedOptions}
onChange={onChangeHandler}
isMulti={true}
/>
);