UNPKG

daily-toolset

Version:

A lightweight, versatile collection of TypeScript utility functions for everyday development needs. Simplify and streamline your Node.js, React, and Next.js projects with a powerful suite of well-organized helpers for strings, arrays, dates, objects, and

45 lines (44 loc) 1.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useWindowScroll = useWindowScroll; const react_1 = require("react"); /** * A hook that returns the current window scroll position and a function to * scroll to the given x and y coordinates. * * @returns {Array} A tuple with the current scroll position and a function to * scroll to the given x and y coordinates. * @example * const [scroll, scrollTo] = useWindowScroll(); * * // scroll to the top of the page * scrollTo({ x: 0, y: 0 }); */ function useWindowScroll() { const [scroll, setScroll] = (0, react_1.useState)({ x: window.scrollX, y: window.scrollY, }); /** * Scrolls the window to the given x and y coordinates. The coordinates are * optional and default to 0. * * @param {Object} options - Options object with x and y properties. * @param {number} [options.x=0] - The x coordinate to scroll to. * @param {number} [options.y=0] - The y coordinate to scroll to. */ function scrollTo({ x = 0, y = 0 }) { window.scrollTo(x, y); } (0, react_1.useEffect)(() => { function handleScroll() { setScroll({ x: window.scrollX, y: window.scrollY, }); } window.addEventListener("scroll", handleScroll); return () => window.removeEventListener("scroll", handleScroll); }, []); return [scroll, scrollTo]; }