Skip to content

Commit

Permalink
feat: support custom scroll options (#95)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
petersendidit authored Jan 29, 2021
1 parent f9e4aac commit 7ad4628
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,12 @@ const {
- `paddingEnd: Integer`
- Defaults to `0`
- The amount of padding in pixels to add to the end of the virtual list
- `onScrollElement: React.useRef(DOMElement)`
- Optional
- Allows using a different element to bind the `onScroll` event to
- `scrollOffsetFn: Function() => number`
- Optional
- This function, if passed, is called on scroll to get the scroll offest rather than using `parentRef`'s `width` or `height`

### Returns

Expand Down
12 changes: 7 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ export function useVirtual({
horizontal,
scrollToFn,
useObserver,
onScrollElement,
scrollOffsetFn,
}) {
const sizeKey = horizontal ? 'width' : 'height'
const scrollKey = horizontal ? 'scrollLeft' : 'scrollTop'
Expand Down Expand Up @@ -69,12 +71,12 @@ export function useVirtual({

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

const element = onScrollElement ? onScrollElement.current : parentRef.current
useIsomorphicLayoutEffect(() => {
const element = parentRef.current
if (!element) { return }

const onScroll = () => {
const scrollOffset = element[scrollKey]
const scrollOffset = scrollOffsetFn ? scrollOffsetFn() : element[scrollKey]
latestRef.current.scrollOffset = scrollOffset
setRange(prevRange => calculateRange(latestRef.current, prevRange))
}
Expand All @@ -90,7 +92,7 @@ export function useVirtual({
return () => {
element.removeEventListener('scroll', onScroll)
}
}, [parentRef.current, scrollKey, size /* required */, outerSize /* required */])
}, [element, scrollKey, size /* required */, outerSize /* required */])

const virtualItems = React.useMemo(() => {
const virtualItems = []
Expand Down Expand Up @@ -185,8 +187,8 @@ export function useVirtual({
align === 'center'
? measurement.start + measurement.size / 2
: align === 'end'
? measurement.end
: measurement.start
? measurement.end
: measurement.start

scrollToOffset(toOffset, { align, ...rest })
},
Expand Down

0 comments on commit 7ad4628

Please sign in to comment.