I have a custom checkbox group input that is build using antd in react(Typescript).
This is in a div whose state (visibility) is controlled using a state, and is shown on the click of a button.
I need an event listener that will modify the state when a click is registered outside this state so that I can hide this.
Tried writing a lot of hooks but unable to figure this out. My div gets hidden also when I click to select/unselect the checkboxes inside the div.
<div className="relative">
<Button
className=" rounded-l-lg bg-white text-base mt-3 min-w-[175px] px-4 h-auto"
onClick={handleClick}
>
{getEntitySelectorPlaceholderText()}
<FaChevronDown className="ml-1" />
</Button>
{visible && (
<div className="absolute z-10 bg-white border-gray-200 mt-2 shadow">
<CheckboxGroup
className="flex justify-center flex-col items-start ml-3 mt-0 min-w-[165px] pt-3 px-3"
options={[{ label: t('allChannels'), value: 'allChannels' }]}
onChange={handleSelectAll}
value={entityItems.length === NO_OF_CHANNELS ? ['allChannels'] : []}
/>
<CheckboxGroup
className="flex justify-center flex-col items-start ml-3 mt-0 min-w-[165px] pb-3 px-3"
options={[
{ label: t('gift'), value: 'gift' },
{ label: t('batch'), value: 'batch' },
{ label: t('partner'), value: 'partner' },
{ label: t('webOrder'), value: 'webOrder' },
{ label: t('inAppOrder'), value: 'inAppOrder' },
{ label: t('partnerOrder'), value: 'partnerOrder' },
]}
onChange={handleChange}
value={checkedItems}
defaultValue={Object.entries(entities || {})
.filter(([_, value]) => {
return value
})
.map(([key]) => {
return key
})}
/>
</div>
)}
</div>
Have tried it on chat gpt and stackoverflow.
>Solution :
You can add the ref to the parent div. <div className="relative" ref={dropDownRef}> and watch the mouse-down event listener.
const dropDownRef = useRef<HTMLDivElement>(null)
const handleClickOutside = (event: MouseEvent) => {
if (dropDownRef.current && !dropDownRef.current.contains(event.target as Node)) {
setVisible(false)
}
}
useEffect(() => {
document.addEventListener('mousedown', handleClickOutside)
return () => {
document.removeEventListener('mousedown', handleClickOutside)
}
}, []) ```