Skip to content

Instantly share code, notes, and snippets.

@gaurangrshah
Created December 14, 2019 21:45
Show Gist options
  • Save gaurangrshah/b28bb44cf2a07aa12f4eae04e757f449 to your computer and use it in GitHub Desktop.
Save gaurangrshah/b28bb44cf2a07aa12f4eae04e757f449 to your computer and use it in GitHub Desktop.
useFocus / EventListener
import { useEffect } from "react";
export default (target = window, type, listener, ...options) => {
// console.table({ target, type, ...options });
// console.log("useListener Ran", type, target);
useEffect(() => {
const targetIsRef = target.hasOwnProperty("current");
const currentTarget = targetIsRef ? target.current : target;
// console.debug("useListener Effect", currentTarget, targetIsRef);
if (currentTarget)
currentTarget.addEventListener(type, listener, ...options);
console.debug(`🌽useListener added`, currentTarget, type);
return () => {
if (currentTarget)
currentTarget.removeEventListener(type, listener, ...options);
console.debug("🌽useListener removed", currentTarget, type);
};
}, [target, type, listener, options]);
};
import React, { useState, createContext } from "react";
import useEventListener from "./useEventListener";
export default function useFocusListener(ref, watchers) {
const [watched, setWatched] = useState(watchers ? watchers : "app");
const [isFocused, setIsFocused] = useState("");
const handleListener = e => {
// listener used to debug focus
e.preventDefault() && e.persist();
if (!e.target.id) return console.debug("notarget in listener");
console.log(`==== mainListener ${e.target.id}===${e.type} === `);
console.debug("element", document.getElementById(e.target.id));
console.warn(watched.some(item => item === e.target.id));
// create useEffect that updates any matches from watched.some to isFocused
};
useEventListener(ref, "focusin", handleListener);
useEventListener(ref, "focusout", handleListener);
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment