T
TanStack3y ago
rare-sapphire

What does scrollMargin do ?

I was going through react , dynamic example for beta version. In that I came across this code
const RowVirtualizerDynamicWindow = () => {
const parentRef = React.useRef<HTMLDivElement>(null)

const parentOffsetRef = React.useRef(0)

React.useLayoutEffect(() => {
parentOffsetRef.current = parentRef.current?.offsetTop ?? 0
}, [])

const virtualizer = useWindowVirtualizer({
count: sentences.length,
estimateSize: () => 45,
scrollMargin: parentOffsetRef.current,
})

return (
<div ref={parentRef} className="List">
<div
style={{
height: virtualizer.getTotalSize(),
width: '100%',
position: 'relative',
}}
>
{virtualizer.getVirtualItems().map((virtualRow) => (
<div
key={virtualRow.key}
data-index={virtualRow.index}
ref={virtualizer.measureElement}
className={virtualRow.index % 2 ? 'ListItemOdd' : 'ListItemEven'}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
transform: `translateY(${virtualRow.start}px)`,
}}
>
<div>
<div>Row {virtualRow.index}</div>
<p>{sentences[virtualRow.index]}</p>
</div>
</div>
))}
</div>
</div>
)
}
const RowVirtualizerDynamicWindow = () => {
const parentRef = React.useRef<HTMLDivElement>(null)

const parentOffsetRef = React.useRef(0)

React.useLayoutEffect(() => {
parentOffsetRef.current = parentRef.current?.offsetTop ?? 0
}, [])

const virtualizer = useWindowVirtualizer({
count: sentences.length,
estimateSize: () => 45,
scrollMargin: parentOffsetRef.current,
})

return (
<div ref={parentRef} className="List">
<div
style={{
height: virtualizer.getTotalSize(),
width: '100%',
position: 'relative',
}}
>
{virtualizer.getVirtualItems().map((virtualRow) => (
<div
key={virtualRow.key}
data-index={virtualRow.index}
ref={virtualizer.measureElement}
className={virtualRow.index % 2 ? 'ListItemOdd' : 'ListItemEven'}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
transform: `translateY(${virtualRow.start}px)`,
}}
>
<div>
<div>Row {virtualRow.index}</div>
<p>{sentences[virtualRow.index]}</p>
</div>
</div>
))}
</div>
</div>
)
}
Here I could not understand why we are passing scrollMargin to useWindowVirtualizer
2 Replies
thirsty-copper
thirsty-copper3y ago
Hi, as in some cases the list doesn't start from top of the page (imho in most cases), basic having some content before, as in this example
<body>
<div style={{ height: 50 }}>My list</div
<div>...list stuff</div>
</body>
<body>
<div style={{ height: 50 }}>My list</div
<div>...list stuff</div>
</body>
By setting scrollMargin: 50 it will be used with scroll offset to correct calculate from where list start when scrolling
rare-sapphire
rare-sapphireOP3y ago
Got it, in my demo I did not have any content above. Therefore I could not figure out use case for it

Did you find this page helpful?