UNPKG

ra-core

Version:

Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React

74 lines 2.46 kB
import { useEffect } from 'react'; import { useLocation } from 'react-router'; import debounce from 'lodash/debounce'; import { useStore } from '../store'; /** * A hook that tracks the scroll position and restores it when the component mounts. * @param storeKey The key under which to store the scroll position in the store * @param debounceMs The debounce time in milliseconds * * @example * import { useRestoreScrollPosition } from 'ra-core'; * * const MyCustomPage = () => { * useRestoreScrollPosition('my-list'); * * return ( * <div> * <h1>My Custom Page</h1> * <VeryLongContent /> * </div> * ); * }; */ export var useRestoreScrollPosition = function (storeKey, debounceMs) { if (debounceMs === void 0) { debounceMs = 250; } var _a = useTrackScrollPosition(storeKey, debounceMs), position = _a[0], setPosition = _a[1]; var location = useLocation(); useEffect(function () { var _a; if (position != null && ((_a = location.state) === null || _a === void 0 ? void 0 : _a._scrollToTop) !== true) { setPosition(undefined); window.scrollTo(0, position); } // We only want to run this effect on mount // eslint-disable-next-line react-hooks/exhaustive-deps }, []); }; /** * A hook that tracks the scroll position and stores it. * @param storeKey The key under which to store the scroll position in the store * @param debounceMs The debounce time in milliseconds * * @example * import { useTrackScrollPosition } from 'ra-core'; * * const MyCustomPage = () => { * useTrackScrollPosition('my-list'); * * return ( * <div> * <h1>My Custom Page</h1> * <VeryLongContent /> * </div> * ); * }; */ export var useTrackScrollPosition = function (storeKey, debounceMs) { if (debounceMs === void 0) { debounceMs = 250; } var _a = useStore(storeKey), position = _a[0], setPosition = _a[1]; useEffect(function () { if (typeof window === 'undefined') { return; } var handleScroll = debounce(function () { setPosition(window.scrollY); }, debounceMs); window.addEventListener('scroll', handleScroll); return function () { window.removeEventListener('scroll', handleScroll); }; }, [debounceMs, setPosition]); return [position, setPosition]; }; //# sourceMappingURL=useRestoreScrollPosition.js.map