| 1 |
import { useEffect, useRef, useState, useCallback } from "@wordpress/element"; |
| 2 |
|
| 3 |
const Select = (props) => { |
| 4 |
const { onChange, options, value, contentWH } = props; |
| 5 |
const [isOpen, setIsOpen] = useState(false); |
| 6 |
const selectRef = useRef(null); |
| 7 |
|
| 8 |
const handleOptionClick = (option) => { |
| 9 |
setIsOpen(false); |
| 10 |
onChange(option.value); |
| 11 |
}; |
| 12 |
|
| 13 |
const handleClickOutside = useCallback((e) => { |
| 14 |
if (selectRef?.current && !selectRef?.current.contains(e.target)) { |
| 15 |
setIsOpen(false); |
| 16 |
} else if ( |
| 17 |
selectRef?.current && |
| 18 |
selectRef?.current.contains(e.target) && |
| 19 |
!e.target.classList?.contains("sp-smart-reserve-button") |
| 20 |
) { |
| 21 |
setIsOpen(selectRef?.current.classList?.contains("open") ? false : true); |
| 22 |
} |
| 23 |
}, []); |
| 24 |
|
| 25 |
useEffect(() => { |
| 26 |
document.addEventListener("mousedown", handleClickOutside); |
| 27 |
return () => document.removeEventListener("mousedown", handleClickOutside); |
| 28 |
}, [handleClickOutside]); |
| 29 |
|
| 30 |
const selectedOption = options?.find((item) => item.value === value); |
| 31 |
|
| 32 |
return ( |
| 33 |
<div ref={selectRef} className={`sp_smart_filter_select ${isOpen ? "open" : ""}`}> |
| 34 |
<div className="sp_smart_filter_selected"> |
| 35 |
{selectedOption ? selectedOption.label : " "} |
| 36 |
<i className="sp-icon-angle-down"></i> |
| 37 |
</div> |
| 38 |
{isOpen && ( |
| 39 |
<ul |
| 40 |
className="sp_smart_filter_select_options" |
| 41 |
style={{ minWidth: contentWH?.width || "100px", maxHeight: contentWH?.height || "160px" }} |
| 42 |
> |
| 43 |
{options.map((option, k) => ( |
| 44 |
<li |
| 45 |
className="sp-smart-reserve-button sp_smart_filter_select_option" |
| 46 |
key={k} |
| 47 |
onClick={() => handleOptionClick(option)} |
| 48 |
> |
| 49 |
{option.label} |
| 50 |
</li> |
| 51 |
))} |
| 52 |
</ul> |
| 53 |
)} |
| 54 |
</div> |
| 55 |
); |
| 56 |
}; |
| 57 |
|
| 58 |
export default Select; |
| 59 |
|