diff --git a/src/@next/Select/Select.tsx b/src/@next/Select/Select.tsx index 168570644..34e97ada6 100644 --- a/src/@next/Select/Select.tsx +++ b/src/@next/Select/Select.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useState } from 'react'; +import React, { useCallback, useEffect, useRef, useState } from 'react'; import { isEmpty } from 'lodash-es'; import { Option, Section } from '../Menu'; import { Popover } from '../Popover'; @@ -101,6 +101,9 @@ export const Select = ({ isPlaceholderFloating, }: SelectProps) => { const [popoverActive, setPopoverActive] = useState(false); + const selectRef = useRef(null); + const popoverRef = useRef(null); + const [optionListHeight, setOptionListHeight] = useState(''); const [menuOptions, setMenuOptions] = useState([]); const { length: optionsLength } = options; @@ -126,6 +129,28 @@ export const Select = ({ setMenuOptions(newState); }; + const handleClickOutside = useCallback((event: MouseEvent) => { + const selectElement = selectRef.current; + const popoverElement = popoverRef.current; + const target = event.target as Node; + + if ( + selectElement && + popoverElement && + !selectElement.contains(target) && + !popoverElement.contains(target) + ) { + setPopoverActive(false); + } + }, []); + + useEffect(() => { + document.addEventListener('mousedown', handleClickOutside); + return () => { + document.removeEventListener('mousedown', handleClickOutside); + }; + }, [handleClickOutside]); + const handleClose = () => { setPopoverActive(false); onClose?.(); @@ -147,7 +172,10 @@ export const Select = ({ }; const handleSelectClick = () => { - setPopoverActive(!popoverActive); + if (!disabled) { + setPopoverActive(true); + } + onSelectClick?.(); }; useEffect( @@ -246,57 +274,59 @@ export const Select = ({ }; return ( - - {label && !isPlaceholderFloating && } - {activator()} - {helpText && ( - - - {helpText} - - - )} - - } - onClose={handleClose} - autofocusTarget="none" - preventFocusOnClose - preferredAlignment="left" - preferredPosition="below" - fullWidth - fitContent={optionListFitContent} - zIndexOverride={zIndexOverride} - > - {!disabled && ( - - - updateSearchableSelectState(newState) - } - /> - - )} - +
+ + {label && !isPlaceholderFloating && } + {activator()} + {helpText && ( + + + {helpText} + + + )} + + } + onClose={handleClose} + autofocusTarget="none" + preventFocusOnClose + preferredAlignment="left" + preferredPosition="below" + fullWidth + fitContent={optionListFitContent} + zIndexOverride={zIndexOverride} + > + {!disabled && ( + + + updateSearchableSelectState(newState) + } + /> + + )} + +
); };