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;