Created
June 27, 2019 16:55
-
-
Save brayhoward/0cfb73ef0c6f75d633e876d64bbf9d4b to your computer and use it in GitHub Desktop.
A React hook for determining whether or not a section of DOM still has the users attention. It's like clickAway logic on steroids
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect, RefObject } from "react"; | |
export default function useAttentionWithin(ref: RefObject<HTMLElement>) { | |
const [attentionWithin, setAttentionWithin] = useState(false); | |
function handleAttentionLeave({ target }: Event) { | |
const targetIsWithin = !!( | |
ref.current && ref.current.contains(target as Node) | |
); | |
setAttentionWithin(targetIsWithin); | |
} | |
useEffect(() => { | |
document.addEventListener("focusin", handleAttentionLeave); | |
document.addEventListener("mouseup", handleAttentionLeave); | |
return () => { | |
document.removeEventListener("focusin", handleAttentionLeave); | |
document.removeEventListener("mouseup", handleAttentionLeave); | |
}; | |
}, []); | |
return attentionWithin; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment