Skip to content

Commit

Permalink
refactor: add window example for react, update docs (#614)
Browse files Browse the repository at this point in the history
  • Loading branch information
piecyk authored Oct 22, 2023
1 parent c940b9e commit cf2e026
Show file tree
Hide file tree
Showing 14 changed files with 639 additions and 67 deletions.
25 changes: 17 additions & 8 deletions docs/api/virtualizer.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,14 +136,6 @@ rangeExtractor?: (range: Range) => number[]

This function receives visible range indexes and should return array of indexes to render. This is useful if you need to add or remove items from the virtualizer manually regardless of the visible range, eg. rendering sticky items, headers, footers, etc. The default range extractor implementation will return the visible range indexes and is exported as `defaultRangeExtractor`.

### `enableSmoothScroll`

```tsx
enableSmoothScroll?: boolean
```

Enables/disables smooth scrolling. Smooth scrolling is enabled by default, but may result in inaccurate landing positions when dynamically measuring elements (a common use case and configuration). If you plan to use smooth scrolling, it's suggested that you either estimate the size of your elements as close to their maximums as possible, or simply turn off dynamic measuring of elements.

### `scrollToFn`

```tsx
Expand Down Expand Up @@ -193,6 +185,15 @@ This optional function is called when the virtualizer needs to dynamically measu

> 🧠 You can use `instance.options.horizontal` to determine if the width or height of the item should be measured.
### `scrollMargin`

```tsx
scrollMargin?: number
```

With this option, you can specify where the scroll offset should originate. Typically, this value represents the space between the beginning of the scrolling element and the start of the list. This is especially useful in common scenarios such as when you have a header preceding a window virtualizer or when multiple virtualizers are utilized within a single scrolling element.


## Virtualizer Instance

The following properties and methods are available on the virtualizer instance:
Expand Down Expand Up @@ -303,3 +304,11 @@ lanes: number
```
The number of lanes the list is divided into (aka columns for vertical lists and rows for horizontal lists).
### `scrollRect`
```tsx
scrollRect: Rect
```
Current `Rect` of the scroll element.
3 changes: 2 additions & 1 deletion docs/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@
{ "to": "examples/react/sticky", "label": "Sticky" },
{ "to": "examples/react/infinite-scroll", "label": "Infinite Scroll" },
{ "to": "examples/react/smooth-scroll", "label": "Smooth Scroll" },
{ "to": "examples/react/table", "label": "Table" }
{ "to": "examples/react/table", "label": "Table" },
{ "to": "examples/react/window", "label": "Window" }
]
},
{
Expand Down
57 changes: 0 additions & 57 deletions examples/react/dynamic/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,61 +99,6 @@ function RowVirtualizerDynamic() {
)
}

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,
})
const items = virtualizer.getVirtualItems()

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

function ColumnVirtualizerDynamic() {
const parentRef = React.useRef<HTMLDivElement | null>(null)

Expand Down Expand Up @@ -366,8 +311,6 @@ function App() {
return <RowVirtualizerDynamic />
case '/columns':
return <ColumnVirtualizerDynamic />
case '/window-list':
return <RowVirtualizerDynamicWindow />
case '/grid': {
const columns = generateColumns(30)
const data = generateData(columns)
Expand Down
5 changes: 5 additions & 0 deletions examples/react/window/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules
.DS_Store
dist
dist-ssr
*.local
6 changes: 6 additions & 0 deletions examples/react/window/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Example

To run this example:

- `npm install` or `yarn`
- `npm run start` or `yarn start`
11 changes: 11 additions & 0 deletions examples/react/window/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
23 changes: 23 additions & 0 deletions examples/react/window/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "window",
"private": true,
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"serve": "vite preview"
},
"dependencies": {
"@tanstack/react-virtual": "3.0.0-beta.66",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@rollup/plugin-replace": "^5.0.2",
"@types/node": "18.x",
"@types/react": "^18.0.27",
"@types/react-dom": "^18.0.10",
"@vitejs/plugin-react": "^3.0.1",
"typescript": "^4.9.5",
"vite": "^4.0.4"
}
}
28 changes: 28 additions & 0 deletions examples/react/window/src/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
html {
font-family: sans-serif;
font-size: 14px;
}

body {
padding: 1rem;
}

.List {
border: 1px solid #e6e4dc;
max-width: 100%;
}

.ListItemEven,
.ListItemOdd {
display: flex;
align-items: center;
justify-content: center;
}

.ListItemEven {
background-color: #e6e4dc;
}

button {
border: 1px solid gray;
}
82 changes: 82 additions & 0 deletions examples/react/window/src/main.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import * as React from 'react'
import * as ReactDOM from 'react-dom/client'

import './index.css'

import { useWindowVirtualizer } from '@tanstack/react-virtual'

function Example() {
const listRef = React.useRef<HTMLDivElement | null>(null)

const virtualizer = useWindowVirtualizer({
count: 10000,
estimateSize: () => 35,
overscan: 5,
scrollMargin: listRef.current?.offsetTop ?? 0,
})

return (
<>
<div ref={listRef} className="List">
<div
style={{
height: `${virtualizer.getTotalSize()}px`,
width: '100%',
position: 'relative',
}}
>
{virtualizer.getVirtualItems().map((item) => (
<div
key={item.key}
className={item.index % 2 ? 'ListItemOdd' : 'ListItemEven'}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: `${item.size}px`,
transform: `translateY(${
item.start - virtualizer.options.scrollMargin
}px)`,
}}
>
Row {item.index}
</div>
))}
</div>
</div>
</>
)
}

function App() {
return (
<div>
<p>
In many cases, when implementing a virtualizer with a window as the
scrolling element, developers often find the need to specify a
"scrollMargin." The scroll margin is a crucial setting that defines the
space or gap between the start of the page and the edges of the list.
</p>
<br />
<br />
<h3>Window scroller</h3>
<Example />
<br />
<br />
{process.env.NODE_ENV === 'development' ? (
<p>
<strong>Notice:</strong> You are currently running React in
development mode. Rendering performance will be slightly degraded
until this application is build for production.
</p>
) : null}
</div>
)
}

ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
12 changes: 12 additions & 0 deletions examples/react/window/tsconfig.dev.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"composite": true,
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./build/types"
},
"files": ["src/main.tsx"],
"include": [
"src"
// "__tests__/**/*.test.*"
]
}
7 changes: 7 additions & 0 deletions examples/react/window/vite.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
})
Loading

0 comments on commit cf2e026

Please sign in to comment.