1 year ago

#384639

test-img

Brandini

React-Select grouped options: how to set and pull value of group title and attach it to options

I've been working with the React-Select component and have been using grouped options to display the groups of color and flavor along with their respective options to select from:

import React, { CSSProperties } from "react";

import Select from "react-select";

const colorOptions = [
  "Red",
  "Blue",
  "Green",
  "Yellow",
  "Orange",
  "Purple",
  "Brown"
].map((o) => ({
  value: o.replace(" ", "_").toLowerCase(),
  label: o
}));

const flavorOptions = [
  "Vanilla", 
  "Chocolate", 
  "Strawberry", 
  "Cookies"
].map((o) => ({
    value: o.replace(" ", "_").toLowerCase(),
    label: o
  }));

const groupedOptions = [
  {
    label: "Colors",
    options: colorOptions
  },
  {
    label: "Flavors",
    options: flavorOptions
  }
];

export default () => (
  <Select options={groupedOptions} onChange={(e) => console.log(e)} />
);

By doing this, we have the following data structure for groupedOptions:

label: "Flavors"
options: Array(4)
    0: {label: "Vanilla", value: "vanilla"}
    1: {label: "Chocolate", value: "chocolate"}
    2: {label: "Strawberry", value: "strawberry"}
    3: {label: "Cookies", value: "cookies"}

However, whenever the console log of the React-Select component activates for the OnChange of the selected value we are only provided this {value: "vanilla", label:"Vanilla"}

I was wondering what would be the best approach to attach the upper groupLabel (Colors or Flavors) to this object or to be able to pull out this value and remap it to appear like the following:

{ 
  label: "Flavors"
  options: {
  value: "vanilla",
  label: "Vanilla"
  }
}

reactjs

typescript

nested

mapping

react-select

0 Answers

Your Answer

Accepted video resources