From 5be380f984be996827552ee644c1b3ad4df87a92 Mon Sep 17 00:00:00 2001 From: Olzhas Alexandrov Date: Thu, 22 Oct 2020 14:57:20 -0500 Subject: [PATCH] feat: Add ability to replace useRect with custom observer (#75) * feat: Add ability to replace useRect with custom observer * fix: naming based on review --- README.md | 6 ++++++ src/index.js | 4 +++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3d662054..dd1692c0 100644 --- a/README.md +++ b/README.md @@ -237,6 +237,7 @@ const { overscan, horizontal, scrollToFn, + useObserver, }) ``` @@ -266,6 +267,11 @@ const { - Optional - This function, if passed, is responsible for implementing the scrollTo log for the parentRef which is used when methods like `scrolllToOffset` and `scrollToIndex` are called. - Eg. You can use this function implement smooth scrolling by using the supplied offset and the `defaultScrollToFn` as seen in the sandbox's **Smooth Scroll** example. +- `useObserver: Function(parentRef) => ({ width: number; height: number })` + - Optional + - This hook, if passed, is responsible for getting `parentRef`'s dimensions + - Eg. You can use this hook to replace [@reach/observe-rect](https://github.com/reach/observe-rect) that `react-virtual` uses by default with [ResizeObserver API](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver) + - Caution! Depending on your bundling target, you might need to add [resize-observer-polyfill](https://www.npmjs.com/package/resize-observer-polyfill) - `paddingStart: Integer` - Defaults to `0` - The amount of padding in pixels to add to the start of the virtual list diff --git a/src/index.js b/src/index.js index fd1d610b..348eb4c6 100644 --- a/src/index.js +++ b/src/index.js @@ -14,12 +14,14 @@ export function useVirtual({ parentRef, horizontal, scrollToFn, + useObserver, }) { const sizeKey = horizontal ? 'width' : 'height' const scrollKey = horizontal ? 'scrollLeft' : 'scrollTop' const latestRef = React.useRef({}) + const useMeasureParent = useObserver || useRect - const { [sizeKey]: outerSize } = useRect(parentRef) || { + const { [sizeKey]: outerSize } = useMeasureParent(parentRef) || { [sizeKey]: 0, }