Skip to content

Instantly share code, notes, and snippets.

@mudssrali
Created March 22, 2021 05:03
Show Gist options
  • Save mudssrali/9f467f413755b6d66affef4967780e94 to your computer and use it in GitHub Desktop.
Save mudssrali/9f467f413755b6d66affef4967780e94 to your computer and use it in GitHub Desktop.

React custom hook to show/hide content based on outside click

import React, { useState, useEffect, useRef } from 'react'

export const useComponentVisible = (isVisible = false) => {
  	// ref of elem for which you want to detect outside click
	const ref = useRef(null)
	const [isComponentVisible, setIsComponentVisible] = useState(isVisible)

	useEffect(() => {
		const handleClickOutside = (e) => {
			if (ref.current && !ref.current.contains(e.target) && isComponentVisible) {
				setIsComponentVisible(false)
			}
		}

		document.addEventListener('click', handleClickOutside, true)
		// cleanup
		return () => {
			document.removeEventListener('click', handleClickOutside, true)
		}
	}, [isComponentVisible])

	return { ref, isComponentVisible, setIsComponentVisible }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment