Skip to content

Instantly share code, notes, and snippets.

@brayhoward
Created June 27, 2019 16:55
Show Gist options
  • Save brayhoward/0cfb73ef0c6f75d633e876d64bbf9d4b to your computer and use it in GitHub Desktop.
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
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