ahooks
Version:
react hooks library
27 lines (26 loc) • 1.07 kB
JavaScript
import { useState } from 'react';
import useEventListener from '../useEventListener';
export default function useFocusWithin(target, options) {
const [isFocusWithin, setIsFocusWithin] = useState(false);
const { onFocus, onBlur, onChange } = options || {};
useEventListener('focusin', (e) => {
if (!isFocusWithin) {
onFocus === null || onFocus === void 0 ? void 0 : onFocus(e);
onChange === null || onChange === void 0 ? void 0 : onChange(true);
setIsFocusWithin(true);
}
}, {
target,
});
useEventListener('focusout', (e) => {
var _a, _b;
if (isFocusWithin && !((_b = (_a = e.currentTarget) === null || _a === void 0 ? void 0 : _a.contains) === null || _b === void 0 ? void 0 : _b.call(_a, e.relatedTarget))) {
onBlur === null || onBlur === void 0 ? void 0 : onBlur(e);
onChange === null || onChange === void 0 ? void 0 : onChange(false);
setIsFocusWithin(false);
}
}, {
target,
});
return isFocusWithin;
}