Skip to content

Commit 7ad4628

Browse files
feat: support custom scroll options (#95)
This adds two new options which make it easier to customize the scroll behavior. `onScrollElement` which makes it possible to use a different element to bind the `onScroll` event too. `scrollOffsetFn` allows a custom function to calculate the offset rather than using the `parentRef`'s width or height.
1 parent f9e4aac commit 7ad4628

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,12 @@ const {
278278
- `paddingEnd: Integer`
279279
- Defaults to `0`
280280
- The amount of padding in pixels to add to the end of the virtual list
281+
- `onScrollElement: React.useRef(DOMElement)`
282+
- Optional
283+
- Allows using a different element to bind the `onScroll` event to
284+
- `scrollOffsetFn: Function() => number`
285+
- Optional
286+
- This function, if passed, is called on scroll to get the scroll offest rather than using `parentRef`'s `width` or `height`
281287

282288
### Returns
283289

src/index.js

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ export function useVirtual({
1515
horizontal,
1616
scrollToFn,
1717
useObserver,
18+
onScrollElement,
19+
scrollOffsetFn,
1820
}) {
1921
const sizeKey = horizontal ? 'width' : 'height'
2022
const scrollKey = horizontal ? 'scrollLeft' : 'scrollTop'
@@ -69,12 +71,12 @@ export function useVirtual({
6971

7072
const [range, setRange] = React.useState({ start: 0, end: 0 })
7173

74+
const element = onScrollElement ? onScrollElement.current : parentRef.current
7275
useIsomorphicLayoutEffect(() => {
73-
const element = parentRef.current
7476
if (!element) { return }
7577

7678
const onScroll = () => {
77-
const scrollOffset = element[scrollKey]
79+
const scrollOffset = scrollOffsetFn ? scrollOffsetFn() : element[scrollKey]
7880
latestRef.current.scrollOffset = scrollOffset
7981
setRange(prevRange => calculateRange(latestRef.current, prevRange))
8082
}
@@ -90,7 +92,7 @@ export function useVirtual({
9092
return () => {
9193
element.removeEventListener('scroll', onScroll)
9294
}
93-
}, [parentRef.current, scrollKey, size /* required */, outerSize /* required */])
95+
}, [element, scrollKey, size /* required */, outerSize /* required */])
9496

9597
const virtualItems = React.useMemo(() => {
9698
const virtualItems = []
@@ -185,8 +187,8 @@ export function useVirtual({
185187
align === 'center'
186188
? measurement.start + measurement.size / 2
187189
: align === 'end'
188-
? measurement.end
189-
: measurement.start
190+
? measurement.end
191+
: measurement.start
190192

191193
scrollToOffset(toOffset, { align, ...rest })
192194
},

0 commit comments

Comments
 (0)