diff --git a/src/Dropdown.tsx b/src/Dropdown.tsx index 827eaec..f9cd735 100644 --- a/src/Dropdown.tsx +++ b/src/Dropdown.tsx @@ -27,21 +27,23 @@ const Dropdown = React.forwardRef(function Dropdo const baseStyle = dropdown.base const alignStyle = dropdown.align[align] - - function handleEsc(e: KeyboardEvent) { - if (e.key === 'Esc' || e.key === 'Escape') { - onClose() - } - } - const dropdownRef = useRef(null) - function handleClickOutside(e: MouseEvent) { - if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) { - onClose() - } - } + + const closeRef = useRef(onClose); + closeRef.current = onClose; useEffect(() => { + function handleEsc(e: KeyboardEvent) { + if (e.key === 'Esc' || e.key === 'Escape') { + closeRef.current() + } + } + function handleClickOutside(e: MouseEvent) { + if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) { + closeRef.current() + } + } + document.addEventListener('click', handleClickOutside, { capture: true }) document.addEventListener('keydown', handleEsc, { capture: true }) return () => {