'Need a cleaner way to close dropdowns when clicked outside of them

I am looking for a cleaner way to close my three dropdowns when I click outside of them. Currently, I am utilizing window.addEventListener('click') with some exclusions to get this done. While it works decently, I do get random errors saying that my event.target is undefined. I haven't had the best luck at repeating the error either. Anyway, my current code is below.

    useEffect(() => {
        // close dropdown on any click outside of button/dropdown/dropdown options
        // these are simple exclusions from the global click - they include dropdowns, dropdown options, and filter/sort buttons
        window.addEventListener("click", e => {
            if (e.path[4].id.includes('filterSortBar') || 
                e.target.id.includes('maxSlider') ||
                e.target.id.includes('minSlider') ||
                e.target.id.includes('minInputContainer') ||
                e.target.id.includes('maxInputContainer') ||
                e.target.type === 'number' ||
                e.path[4].id.includes('filterButtonsContainer') ||
                e.path[4].id.includes('relativeContainer') || 
                e.target.textContent === 'Relevance' || 
                e.target.textContent === 'Retailers' &&
                !e.target.className.includes('buttonPadding')){
            } else {
                setAddFilterTruthy(false)
                setSortTruthy(false)
                setPriceTruthy(false)
            }
    })
}, []);

The ugliness is glaring. Basically, if the click does not contain the element, I set the truthy value to false and the dropdown closes appropriately.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source