hi
- User
hi
- Assistant
Hello! How may I assist you today?
- User
i have a react multi-select component that has 2 groups. selecting items from multiple groups should not be possible. how do i do that ?
- Assistant
To prevent selecting items from multiple groups in a React multi-select component, you can check the selected items' group in the
onChangeevent handler and remove the previously selected items if the selected item is from a different group.Here's an example implementation:
import React, { useState } from "react"; const MultiSelect = ({ options }) => { const [selectedItems, setSelectedItems] = useState([]); const handleSelect = (itemId, itemGroup) => { const selectedItem = { id: itemId, group: itemGroup }; const newSelection = [...selectedItems, selectedItem]; // Find previously selected items in a different group and remove them const prevGroup = selectedItems[0]?.group; if (prevGroup && prevGroup !== itemGroup) { setSelectedItems(newSelection.filter((item) => item.group === itemGroup)); } else { setSelectedItems(newSelection); } }; return ( <div> {options.map((group) => ( <div key={group.label}> <p>{group.label}</p> {group.options.map((option) => ( <label key={option.id}> <input type="checkbox" checked={selectedItems.some((item) => item.id === option.id)} onChange={() => handleSelect(option.id, group.label)} /> {option.label} </label> ))} </div> ))} </div> ); }; export default MultiSelect;
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.