mui-chip-select
Version:
A react component for building selectable MUI Chips
54 lines • 2.84 kB
JavaScript
import { __assign, __spreadArray } from "tslib";
import React, { useState } from 'react';
import Chip from '@mui/material/Chip';
import Stack from '@mui/material/Stack';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
function MuiChipSelect(_a) {
var options = _a.options, onChange = _a.onChange, chipProps = _a.chipProps, className = _a.className;
var _b = useState([]), selected = _b[0], setSelected = _b[1];
function handleChipClick(option) {
var newSelected = [];
if (typeof option === 'string') {
var selectedIndex = selected.indexOf(option);
if (selectedIndex === -1) {
newSelected = __spreadArray(__spreadArray([], selected, true), [option], false);
}
else if (selectedIndex === 0) {
newSelected = selected.slice(1);
}
else if (selectedIndex === selected.length - 1) {
newSelected = selected.slice(0, -1);
}
else if (selectedIndex > 0) {
newSelected = __spreadArray(__spreadArray([], selected.slice(0, selectedIndex), true), selected.slice(selectedIndex + 1), true);
}
}
else {
var selectedIndex = selected.findIndex(function (opt) {
return typeof opt === 'string' ? opt === option.label : opt.value === option.value;
});
if (selectedIndex === -1) {
newSelected = __spreadArray(__spreadArray([], selected, true), [option], false);
}
else if (selectedIndex === 0) {
newSelected = selected.slice(1);
}
else if (selectedIndex === selected.length - 1) {
newSelected = selected.slice(0, -1);
}
else if (selectedIndex > 0) {
newSelected = __spreadArray(__spreadArray([], selected.slice(0, selectedIndex), true), selected.slice(selectedIndex + 1), true);
}
}
setSelected(newSelected);
onChange(newSelected);
}
var optionList = options.map(function (option) { return (typeof option === 'string' ? { label: option, value: option } : option); });
return (React.createElement(Stack, { direction: 'row', spacing: 1, className: className }, optionList.map(function (option) { return (React.createElement(Chip, __assign({ key: option.value, label: option.label, clickable: true, icon: React.createElement(CheckCircleIcon, null), onClick: function () { return handleChipClick(option); }, color: selected.findIndex(function (opt) {
return typeof opt === 'string' ? opt === option.label : opt.value === option.value;
}) !== -1
? 'primary'
: 'default' }, chipProps))); })));
}
export default MuiChipSelect;
//# sourceMappingURL=App.js.map