Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

71
Views
How to get group of selected value in react-select

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}
  />
);
7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

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}
  />
);
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.