From cdec17735fee551878529d0b1509951c2cc72a73 Mon Sep 17 00:00:00 2001 From: Pramod Mahajan Date: Sun, 18 May 2025 02:13:38 +0530 Subject: [PATCH] created new component SelectMultiple items --- src/components/common/SelectMultiple.jsx | 125 +++++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 src/components/common/SelectMultiple.jsx diff --git a/src/components/common/SelectMultiple.jsx b/src/components/common/SelectMultiple.jsx new file mode 100644 index 00000000..e0c47760 --- /dev/null +++ b/src/components/common/SelectMultiple.jsx @@ -0,0 +1,125 @@ +import React, { useState, useEffect, useRef } from 'react'; +import { useFormContext } from 'react-hook-form'; +import './MultiSelectDropdown.css'; + +const SelectMultiple = ({ + name, + options = [], + label = 'Select options', + labelKey = 'name', + valueKey = 'id', + placeholder = 'Please select...', + IsLoading = false +}) => { + const { setValue, watch } = useFormContext(); + const selectedValues = watch(name) || []; + + const [isOpen, setIsOpen] = useState(false); + const [searchText, setSearchText] = useState(''); + const dropdownRef = useRef(null); + + useEffect(() => { + const handleClickOutside = (e) => { + if (dropdownRef.current && !dropdownRef.current.contains(e.target)) { + setIsOpen(false); + } + }; + document.addEventListener('mousedown', handleClickOutside); + return () => document.removeEventListener('mousedown', handleClickOutside); + }, []); + + const handleCheckboxChange = (value) => { + const updated = selectedValues.includes(value) + ? selectedValues.filter((v) => v !== value) + : [...selectedValues, value]; + + setValue(name, updated, { shouldValidate: true }); + }; + + const filteredOptions = options.filter((item) => + item[labelKey]?.toLowerCase().includes(searchText.toLowerCase()) + ); + + return ( +
+ + +
setIsOpen((prev) => !prev)} +> + 0 + ? 'placeholder-style-selected' + : 'placeholder-style' + } + > +
+ {selectedValues.length > 0 ? ( + selectedValues.map((val) => { + const found = options.find((opt) => opt[valueKey] === val); + return ( + + {found ? found[labelKey] : ''} + + ); + }) + ) : ( + {placeholder} + )} +
+
+ +
+ + + {isOpen && ( +
+
+ setSearchText(e.target.value)} + className="multi-select-dropdown-search-input" + /> +
+ + {filteredOptions.map((item) => { + const labelVal = item[labelKey]; + const valueVal = item[valueKey]; + const isChecked = selectedValues.includes(valueVal); + + return ( +
+ handleCheckboxChange(valueVal)} + /> + +
+ ); + } )} + {!IsLoading && filteredOptions.length === 0 && ( +
+ +
+ )} + {IsLoading && filteredOptions.length === 0 && ( +
+ +
+ )} +
+ )} +
+ ); +}; + +export default SelectMultiple;