@gravitywelluk/react-hooks
Version:
Library of commonly used React hooks
80 lines (79 loc) • 3.07 kB
JavaScript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useScrollPosition = void 0;
const React = __importStar(require("react"));
// Initial scroll position
const initialScrollPosition = {
x: undefined,
y: undefined
};
/**
* Scroll position hook
*/
const useScrollPosition = (element) => {
const isClient = typeof window === "object";
const target = React.useMemo(() => isClient ? element && element.current ? element.current : document.body : null, [element, isClient]);
const [initialised, setInitialised] = React.useState(false);
const [scrollPosition, setScrollPostion] = React.useState(initialScrollPosition);
/**
* Updates the scroll position when called
*/
const updateScrollPosition = React.useCallback(() => {
const position = target === null || target === void 0 ? void 0 : target.getBoundingClientRect();
// If position exists
if (position) {
const x = position.left < 0 ? Math.abs(position.left) : -Math.abs(position.left);
const y = position.top < 0 ? Math.abs(position.top) : -Math.abs(position.top);
setScrollPostion({
x,
y
});
}
}, [target]);
//
React.useEffect(() => {
// If window client exists and the scroll position have not been initialised,
// set them and update state.
if (isClient && !initialised) {
// Update the initialised state
setInitialised(true);
// Initialise the scroll position
updateScrollPosition();
// Add "resize" event listener
window.addEventListener("scroll", updateScrollPosition);
}
// On unmount, remove the "resize" event listener
return () => {
// If window client exists and the dimensions have been initialised
if (isClient && initialised) {
window.removeEventListener("scroll", updateScrollPosition);
}
};
}, [
initialised,
isClient,
target,
updateScrollPosition
]);
return scrollPosition;
};
exports.useScrollPosition = useScrollPosition;
;