Mulit Select , Select2 in MUI | React | Material UI
Copy Below Code
View As A Text File
Show Text Only
Show API
Edit Code
===== Component ====
import React from "react";
import { Box } from "@material-ui/core";
import { createStyles, makeStyles, Theme } from "@material-ui/core/styles";
import Multiselect from "multiselect-react-dropdown";
const useStyles = makeStyles((theme: Theme) => createStyles({}));
const MenuProps = {
PaperProps: {},
getContentAnchorEl: null,
};
interface Props {
allValues: any;
onSelect: any;
onRemove?: any;
selctedItems?: any;
errorText?: any;
displayValue?: any;
placeholder?: any;
}
export default function MultiSelect2({
allValues,
onSelect,
onRemove,
selctedItems,
errorText,
displayValue,
placeholder,
}: Props) {
const classes = useStyles();
return (
<div>
<Box>
<Multiselect
showCheckbox={true}
closeOnSelect={true}
options={allValues}
selectedValues={selctedItems}
displayValue={displayValue}
onSelect={onSelect}
onRemove={onRemove}
placeholder={placeholder}
/>
<span style={{ color: "red" }}>{errorText} </span>
</Box>
</div>
);
}
============= Component Calling , home.js============
roles: Yup.array<string[]>().min(1, "At least one role is required."),
/* NEW MultiSelect */
const [selctedItems, setSelctedItems] = React.useState<any>([]);
React.useEffect(() => {
if (currentUser?.roles) {
const arr = currentUser?.roles;
setSelctedItems(arr);
formik.setFieldValue(
"roles",
arr.map((item: any) => (item.id ? item.id : ""))
);
}
}, [currentUser]);
const onMultiSelectSelection = (selectedList: any, selectedItem: any) => {
formik.setFieldValue(
"roles",
selectedList.map((item: any) => (item.id ? item.id : ""))
);
};
const onMultiSelectRemove = (selectedList: any, removedItem: any) => {
formik.setFieldValue(
"roles",
selectedList.map((item: any) => (item.id ? item.id : ""))
);
};
<MultiSelect2
allValues={allRoles}
selctedItems={selctedItems}
displayValue={"roleName"}
placeholder="User Roles"
onSelect={onMultiSelectSelection}
onRemove={onMultiSelectRemove}
errorText={formik.errors.roles}
/>