简体   繁体   中英

how to filter if label / value has been selected in react select?

how to filter if label / value has been selected in react select?

first I have a list of options (from the API) as follows:

const listFoodSelect = [
   {foodID: 123, label: 'food 1'},
   {foodID: 456, label: 'food 2'},
   {foodID: 789, label: 'food 3'},
   {foodID: 321, label: 'food 4'},
   {foodID: 234, label: 'food 5'}
];

Then I want if one of the labels / values that I have selected does not appear in the listFoodSelect, for example, I select foodID 234, how do I filter the list if the label / value has been selected?

expectations are as follows:

const listFoodSelect = [
   {foodID: 123, label: 'food 1'},
   {foodID: 456, label: 'food 2'},
   {foodID: 789, label: 'food 3'},
   {foodID: 321, label: 'food 4'},
];

this is a initial state

const [menuName, setMenuName] = useState('')
const [listFoodSelect, setListFoodSelect] = useState([])

This is a function to adjust if the value is selected

const onSelectMenu = (indexItem, indexFood) => event => {
    let { foodId, label } = event
    let data = [...listData]
    setMenuName(event.label)
    setListFoodSelect(listFoodSelect.filter(item => item.foodName !== label))
}

and this is the react-select component that has been returned

<Select
   onChange={onSelectMenu(indexItem, indexFood)}
   options={listFoodSelect.filter((option) => option.label !== menuName)}
   value={menuName}
/>

See this codesandbox I have created. Let me know if you have questions

https://codesandbox.io/s/wispy-violet-yv5yt?file=/src/App.js

You should use isMulti prop. It allows you to select more than one item. Once an item is selected, it will be removed from the list of the select dropdown menu.

import React, { useState } from "react";
import Select from "react-select";
import "./styles.css";

export default function App() {
  const listFoodOptions = [
    { value: 123, label: "food 1" },
    { value: 456, label: "food 2" },
    { value: 789, label: "food 3" },
    { value: 321, label: "food 4" },
    { value: 234, label: "food 5" }
  ];

  const [selectedFoods, setSelectedFoods] = useState([]);

  const handleSelect = (newlySelectedFoods) => {
    setSelectedFoods(newlySelectedFoods);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <Select
        onChange={handleSelect}
        options={listFoodOptions}
        isMulti
        value={selectedFoods}
      />
    </div>
  );
}

When isMulti prop is used, the value will be an array of selected items.

See this code sandbox I have created.

https://codesandbox.io/s/quiet-butterfly-vfxwi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM