beautiful-react-hooks
Version:
A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development
49 lines (48 loc) • 1.97 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("react");
var isClient_1 = __importDefault(require("./shared/isClient"));
var isAPISupported_1 = __importDefault(require("./shared/isAPISupported"));
var isDevelopment_1 = __importDefault(require("./shared/isDevelopment"));
var warnOnce_1 = __importDefault(require("./shared/warnOnce"));
var defaultOptions = {
rootMargin: '0px',
threshold: 0
};
var errorMessage = 'IntersectionObserver is not supported, this could happen both because' +
' window.IntersectionObserver is not supported by' +
' your current browser or you\'re using the useViewportSpy hook whilst server side rendering.' +
' This message is displayed only in development mode';
/**
* Uses the IntersectionObserverMock API to tell whether the given DOM Element (from useRef) is visible within the
* viewport.
*/
var useViewportSpy = function (ref, options) {
if (options === void 0) { options = defaultOptions; }
if (!isClient_1.default || !(0, isAPISupported_1.default)('IntersectionObserver')) {
if (isDevelopment_1.default) {
(0, warnOnce_1.default)(errorMessage);
}
return false;
}
var _a = (0, react_1.useState)(), isVisible = _a[0], setIsVisible = _a[1];
(0, react_1.useLayoutEffect)(function () {
var observer = new window.IntersectionObserver(function (entries) {
entries.forEach(function (item) {
var nextValue = item.isIntersecting;
setIsVisible(nextValue);
});
}, options);
if (ref.current) {
observer.observe(ref.current);
}
return function () {
observer.disconnect();
};
}, [ref]);
return isVisible;
};
exports.default = useViewportSpy;