### Install Dependencies Source: https://github.com/bvaughn/react-window/blob/main/CONTRIBUTING.md Run this command to install project dependencies before starting local development. ```sh pnpm install ``` -------------------------------- ### Install react-window Source: https://github.com/bvaughn/react-window/blob/main/README.md Install the library using npm. This is the first step to using react-window in your project. ```sh npm install react-window ``` -------------------------------- ### Run Documentation Site Locally Source: https://github.com/bvaughn/react-window/blob/main/CONTRIBUTING.md Start the local development server for the documentation site. This site runs on localhost port 3000. ```sh pnpm dev ``` -------------------------------- ### Update Generated Assets Source: https://github.com/bvaughn/react-window/blob/main/CONTRIBUTING.md Commands to update generated documentation and examples before submitting changes. These steps are often enforced by CI. ```sh pnpm compile pnpm prettier pnpm lint ``` -------------------------------- ### Run Next.js Development Server Source: https://github.com/bvaughn/react-window/blob/main/integrations/next/README.md Use these commands to start the development server for your Next.js application. Open http://localhost:3000 in your browser to view the result. ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` -------------------------------- ### useListRef for Typed List Imperative API Source: https://context7.com/bvaughn/react-window/llms.txt Use this hook to get a typed ref for the List component's imperative API, allowing access to methods like scrollToRow and the underlying DOM element. ```tsx import { List, useListRef, type RowComponentProps } from "react-window"; type RowProps = { items: string[] }; function RowComponent({ index, items, style }: RowComponentProps) { return
{items[index]}
; } const items = Array.from({ length: 5000 }, (_, i) => `Item ${i}`); function App() { const listRef = useListRef(null); function scrollToMiddle() { listRef.current?.scrollToRow({ index: Math.floor(items.length / 2), align: "center", // "auto" | "center" | "end" | "smart" | "start" behavior: "smooth", // "auto" | "instant" | "smooth" }); } function scrollToTop() { listRef.current?.scrollToRow({ index: 0, align: "start" }); } return ( <>
); } ``` -------------------------------- ### Use `useGridCallbackRef` for Shared Grid API Access Source: https://context7.com/bvaughn/react-window/llms.txt Use `useGridCallbackRef` to get a stateful ref for the `Grid` component's imperative API. This is useful for sharing the API with other hooks or components as a React state value. ```tsx import { Grid, useGridCallbackRef, type GridImperativeAPI } from "react-window"; import type { CellComponentProps } from "react-window"; type CellProps = { data: string[][] }; function CellComponent({ columnIndex, rowIndex, data, style }: CellComponentProps) { return
{data[rowIndex]?.[columnIndex]}
; } function useGridActions(grid: GridImperativeAPI | null) { return { goToOrigin: () => grid?.scrollToCell({ rowIndex: 0, columnIndex: 0, behavior: "smooth" }), }; } const data = Array.from({ length: 500 }, (_, r) => Array.from({ length: 20 }, (_, c) => `${r},${c}`) ); function App() { const [grid, setGrid] = useGridCallbackRef(null); const { goToOrigin } = useGridActions(grid); return ( <>
); } ``` -------------------------------- ### Create New Vike Project Source: https://github.com/bvaughn/react-window/blob/main/integrations/vike/README.md Use this command to generate a new Vike project with React and Tailwind CSS integration. ```sh npm create vike@latest --- --react --tailwindcss ``` -------------------------------- ### Server-Side Rendering (SSR) with `defaultHeight` and `defaultWidth` Source: https://context7.com/bvaughn/react-window/llms.txt For server-side rendering, use `defaultHeight` for Lists and `defaultWidth` for Grids to provide initial dimensions when a DOM is not available for measurement. This ensures meaningful content on the first hydrated paint. ```tsx import { List, Grid, type RowComponentProps, type CellComponentProps } from "react-window"; // --- List with SSR --- type RowProps = { items: string[] }; function RowComponent({ index, items, style }: RowComponentProps) { return
{items[index]}
; } const items = Array.from({ length: 10_000 }, (_, i) => `Row ${i}`); function ServerRenderedList() { return ( ); } // --- Grid with SSR --- type CellProps = { data: string[][] }; function CellComponent({ columnIndex, rowIndex, data, style }: CellComponentProps) { return
{data[rowIndex]?.[columnIndex]}
; } const data = Array.from({ length: 5000 }, (_, r) => Array.from({ length: 20 }, (_, c) => `R${r}C${c}`) ); function ServerRenderedGrid() { return ( ); } ``` -------------------------------- ### Run Unit Tests Locally Source: https://github.com/bvaughn/react-window/blob/main/CONTRIBUTING.md Execute the project's unit tests to ensure code integrity. ```sh pnpm test ``` -------------------------------- ### List Component Source: https://github.com/bvaughn/react-window/blob/main/README.md Renders data with many rows efficiently. It requires specific props for row rendering and data count. ```APIDOC ## List Component ### Description Renders data with many rows. ### Props #### Required Props - **rowComponent** (React Component) - Required - A React component responsible for rendering a row. It receives `index` and `style` props by default, and any props passed to `rowProps`. The prop types are exported as `RowComponentProps`. - **rowCount** (number) - Required - The total number of items to be rendered in the list. - **rowHeight** (number | string | function | object) - Required - The height of each row. Supported formats include: number of pixels, percentage of grid height (string), a function returning row height given an index and `cellProps`, or a dynamic row height cache from `useDynamicRowHeight` hook. Dynamic heights are less efficient. - **rowProps** (object) - Required - Additional props to be passed to the row-rendering component. The list re-renders rows when values in this object change. This object must not contain `ariaAttributes`, `index`, or `style` props. #### Optional Props - **className** (string) - Optional - CSS class name for the list container. - **style** (object) - Optional - Optional CSS properties. The list of rows will fill the height defined by this style. - **children** (React Node) - Optional - Additional content to be rendered within the list (above cells), such as overlays or tooltips. - **defaultHeight** (number) - Optional - Default height of the list for initial render, important for server rendering. - **listRef** (Ref) - Optional - Ref used to interact with the component's imperative API, including scrolling methods and a getter for the outermost DOM element. `useListRef` and `useListCallbackRef` hooks are exported for convenience. - **onResize** (function) - Optional - Callback notified when the List's outermost HTMLElement resizes. Can be used to scroll a row into view. - **onRowsRendered** (function) - Optional - Callback notified when the range of visible rows changes. - **overscanCount** (number) - Optional - Number of additional rows to render outside of the visible area to reduce flickering near edges during scrolling. - **tagName** (string) - Optional - Can be used to override the root HTML element rendered by the List component. Defaults to 'div'. Not typically needed as default ARIA roles are usually sufficient. ``` -------------------------------- ### Grid as a Horizontal List Source: https://context7.com/bvaughn/react-window/llms.txt Configure the Grid with `rowCount={1}` and `rowHeight="100%"` to create a horizontally scrolling list. Useful for displaying cards or thumbnails. ```tsx import { Grid, type CellComponentProps } from "react-window"; type CellProps = { emails: string[] }; function CellComponent({ columnIndex, emails, style }: CellComponentProps) { return (
{emails[columnIndex]}
); } const emails = Array.from({ length: 500 }, (_, i) => `user${i}@example.com`); function App() { return (
); } ``` -------------------------------- ### Grid Component Source: https://github.com/bvaughn/react-window/blob/main/README.md Renders data with many rows and columns. Unlike List, cell sizes must be known ahead of time. ```APIDOC ## Grid Component ### Description Renders data with many rows and columns. ℹ️ Unlike `List` rows, `Grid` cell sizes must be known ahead of time. Either static sizes or something that can be derived (from the data in `CellProps`) without rendering. ``` -------------------------------- ### Add React-Specific ESLint Rules Source: https://github.com/bvaughn/react-window/blob/main/integrations/vite/README.md Integrate `eslint-plugin-react-x` and `eslint-plugin-react-dom` to enable React-specific lint rules. Add the plugins to the `plugins` object and extend their recommended TypeScript and DOM rules. ```javascript // eslint.config.js import reactX from "eslint-plugin-react-x"; import reactDom from "eslint-plugin-react-dom"; export default tseslint.config({ plugins: { // Add the react-x and react-dom plugins "react-x": reactX, "react-dom": reactDom }, rules: { // other rules... // Enable its recommended typescript rules ...reactX.configs["recommended-typescript"].rules, ...reactDom.configs.recommended.rules } }); ``` -------------------------------- ### Grid with Function-Based Column Widths Source: https://context7.com/bvaughn/react-window/llms.txt Use a function for `columnWidth` to dynamically calculate widths based on cell content or other data. This avoids a separate layout pass. ```tsx import { Grid, type CellComponentProps } from "react-window"; type CellProps = { headers: string[]; rows: string[][] }; function CellComponent({ columnIndex, rowIndex, headers, rows, style }: CellComponentProps) { const content = rowIndex === 0 ? headers[columnIndex] : rows[rowIndex - 1][columnIndex]; return (
{content}
); } const headers = ["ID", "First Name", "Last Name", "Email", "Department", "Salary"]; const rows = Array.from({ length: 5000 }, (_, i) => [`${i}`, `First${i}`, `Last${i}`, `user${i}@co.com`, "Engineering", "$100,000`] ); // Column widths derived from the header label length function columnWidth(index: number, { headers }: CellProps): number { return Math.max(80, headers[index].length * 12); } function App() { return (
(i === 0 ? 40 : 30)} style={{ height: 500 }} />
); } ``` -------------------------------- ### Grid Component Source: https://context7.com/bvaughn/react-window/llms.txt A virtualized two-dimensional grid component that renders only the visible cells, optimized for large datasets. Requires fixed cell sizes. ```APIDOC ## `` — Virtualized two-dimensional grid Renders rows and columns of cells, only mounting those visible in both axes. Requires `cellComponent`, `cellProps`, `columnCount`, `columnWidth`, `rowCount`, and `rowHeight`. Cell sizes must be known ahead of time (no dynamic height support). The outer element carries `role="grid"` with `aria-rowcount`/`aria-colcount`; each row gets `role="row"` with `aria-rowindex`; each cell gets `role="gridcell"` with `aria-colindex`. ```tsx import { Grid, type CellComponentProps } from "react-window"; type Contact = { name: string; email: string; phone: string; city: string; state: string }; type CellProps = { contacts: Contact[] }; const COLUMNS = ["name", "email", "phone", "city", "state"] as const; function CellComponent({ columnIndex, rowIndex, contacts, style, }: CellComponentProps) { const contact = contacts[rowIndex]; const value = contact[COLUMNS[columnIndex]]; return (
{value}
); } const contacts: Contact[] = Array.from({ length: 10_000 }, (_, i) => ({ name: `Person ${i}`, email: `person${i}@example.com`, phone: "555-0100", city: "Springfield", state: "IL", })); function App() { return (
); } ``` ``` -------------------------------- ### Grid Required Props Source: https://github.com/bvaughn/react-window/blob/main/README.md These are the essential props that must be provided when using the Grid component. ```APIDOC ## Grid Required Props ### Description These props are mandatory for the Grid component to function correctly. ### Props - **cellComponent** (React Component) - The component used to render each cell. Receives `index`, `style`, and `cellProps`. - **cellProps** (object) - Additional props passed to the `cellComponent`. Must not contain `ariaAttributes`, `columnIndex`, `rowIndex`, or `style`. - **columnCount** (number) - The total number of columns in the grid. - **columnWidth** (number | string | function) - The width of each column. Can be pixels (number), percentage (string), or a function returning width based on index and `cellProps`. - **rowCount** (number) - The total number of rows in the grid. - **rowHeight** (number | string | function) - The height of each row. Can be pixels (number), percentage (string), or a function returning height based on index and `cellProps`. ``` -------------------------------- ### useListRef Source: https://context7.com/bvaughn/react-window/llms.txt Provides a typed ref for the List component's imperative API, allowing direct access to methods like scrollToRow and the underlying DOM element. ```APIDOC ## `useListRef` — Typed ref for `List` imperative API Returns a typed `MutableRefObject` for use with TypeScript. The imperative API exposes `scrollToRow({ index, align?, behavior? })` and a `.element` getter for the underlying DOM node. ```tsx import { List, useListRef, type RowComponentProps } from "react-window"; type RowProps = { items: string[] }; function RowComponent({ index, items, style }: RowComponentProps) { return
{items[index]}
; } const items = Array.from({ length: 5000 }, (_, i) => `Item ${i}`); function App() { const listRef = useListRef(null); function scrollToMiddle() { listRef.current?.scrollToRow({ index: Math.floor(items.length / 2), align: "center", // "auto" | "center" | "end" | "smart" | "start" behavior: "smooth", // "auto" | "instant" | "smooth" }); } function scrollToTop() { listRef.current?.scrollToRow({ index: 0, align: "start" }); } return ( <>
); } ``` ``` -------------------------------- ### Grid with RTL Layout Source: https://context7.com/bvaughn/react-window/llms.txt Enable right-to-left layout by passing `dir="rtl"` to the Grid component. This correctly reverses scroll direction and cell positioning for RTL languages. ```tsx import { Grid, type CellComponentProps } from "react-window"; type CellProps = { data: string[][] }; function CellComponent({ columnIndex, rowIndex, data, style }: CellComponentProps) { return (
{data[rowIndex]?.[columnIndex]}
); } const data = Array.from({ length: 100 }, (_, r) => Array.from({ length: 10 }, (_, c) => `عمود ${c + 1} صف ${r + 1}`) ); function App() { return (
); } ``` -------------------------------- ### Virtualized Vertical List with Variable Row Heights Source: https://context7.com/bvaughn/react-window/llms.txt When rows have varying heights that can be pre-computed, provide a function to `rowHeight`. This function receives the row `index` and `rowProps`, allowing dynamic height calculation based on item data. Ensure the parent container has a bounded height for scrolling. ```tsx import { List, type RowComponentProps } from "react-window"; type Item = { type: "header"; label: string } | { type: "row"; value: string }; type RowProps = { items: Item[] }; // Height function — called before rendering to virtualise correctly function rowHeight(index: number, { items }: RowProps): number { return items[index].type === "header" ? 40 : 25; } function RowComponent({ index, items, style }: RowComponentProps) { const item = items[index]; return (
{item.type === "header" ? item.label : item.value}
); } const items: Item[] = [ { type: "header", label: "Section A" }, ...Array.from({ length: 500 }, (_, i) => ({ type: "row" as const, value: `Row ${i}` })), ]; function App() { return (
rowComponent={RowComponent} rowCount={items.length} rowHeight={rowHeight} rowProps={{ items }} style={{ height: 500 }} />
); } ``` -------------------------------- ### useGridRef Source: https://context7.com/bvaughn/react-window/llms.txt Returns a typed `MutableRefObject` for programmatic scrolling. The API exposes `scrollToCell`, `scrollToRow`, and `scrollToColumn`. ```APIDOC ## `useGridRef` — Typed ref for `Grid` imperative API Returns a typed `MutableRefObject` for programmatic scrolling. The API exposes `scrollToCell`, `scrollToRow`, and `scrollToColumn`. ```tsx import { Grid, useGridRef, type CellComponentProps } from "react-window"; type CellProps = { data: string[][] }; function CellComponent({ columnIndex, rowIndex, data, style }: CellComponentProps) { return
{data[rowIndex]?.[columnIndex]}
; } const data = Array.from({ length: 1000 }, (_, r) => Array.from({ length: 50 }, (_, c) => `R${r}C${c}`) ); function App() { const gridRef = useGridRef(null); function jumpToCell(rowIndex: number, columnIndex: number) { gridRef.current?.scrollToCell({ rowIndex, columnIndex, rowAlign: "center", // "auto" | "center" | "end" | "smart" | "start" columnAlign: "start", behavior: "smooth", }); } function jumpToColumn(index: number) { gridRef.current?.scrollToColumn({ index, align: "start" }); } function jumpToRow(index: number) { gridRef.current?.scrollToRow({ index, align: "center", behavior: "instant" }); } return ( <>
); } ``` ``` -------------------------------- ### Expand ESLint for Type-Aware Rules Source: https://github.com/bvaughn/react-window/blob/main/integrations/vite/README.md Update your ESLint configuration to include type-aware lint rules for production applications. Ensure `tsconfig.node.json` and `tsconfig.app.json` are specified in `parserOptions.project`. ```javascript export default tseslint.config({ extends: [ // Remove ...tseslint.configs.recommended and replace with this ...tseslint.configs.recommendedTypeChecked, // Alternatively, use this for stricter rules ...tseslint.configs.strictTypeChecked, // Optionally, add this for stylistic rules ...tseslint.configs.stylisticTypeChecked ], languageOptions: { // other options... parserOptions: { project: ["./tsconfig.node.json", "./tsconfig.app.json"], tsconfigRootDir: import.meta.dirname } } }); ``` -------------------------------- ### useListCallbackRef Source: https://context7.com/bvaughn/react-window/llms.txt Provides a ref callback for sharing the List component's imperative API, returning a stateful value that can be passed to other hooks or components. ```APIDOC ## `useListCallbackRef` — Ref callback for sharing List API Returns a `[value, setter]` pair (backed by `useState`) so the `ListImperativeAPI` instance can be read as a plain state value and passed to other hooks or child components. ```tsx import { List, useListCallbackRef, type ListImperativeAPI } from "react-window"; import type { RowComponentProps } from "react-window"; type RowProps = { items: string[] }; function RowComponent({ index, items, style }: RowComponentProps) { return
{items[index]}
; } // A hook that consumes the imperative API function useScrollReset(list: ListImperativeAPI | null) { return () => list?.scrollToRow({ index: 0 }); } const items = Array.from({ length: 1000 }, (_, i) => `Item ${i}`); function App() { // list is the current value; setList is the ref callback passed to const [list, setList] = useListCallbackRef(null); const resetScroll = useScrollReset(list); return ( <>
); } ``` ``` -------------------------------- ### Grid Optional Props Source: https://github.com/bvaughn/react-window/blob/main/README.md These are optional props that can be used to customize the Grid component's appearance and behavior. ```APIDOC ## Grid Optional Props ### Description These props provide additional customization and control over the Grid component's behavior and appearance. ### Props - **className** (string) - CSS class name for the grid container. - **dir** (string) - Specifies the text directionality of grid cells (e.g., 'ltr', 'rtl'). - **style** (object) - Optional CSS properties to style the grid container. Determines the fillable height and width. - **children** (ReactNode) - Additional content to render within the grid, above the cells. - **defaultHeight** (number) - Default height for server rendering. - **defaultWidth** (number) - Default width for server rendering. - **gridRef** (Ref) - Imperative reference to the Grid API. Hooks like `useGridRef` are available. - **onCellsRendered** (function) - Callback function invoked when the range of rendered cells changes. - **onResize** (function) - Callback function invoked when the Grid's outermost element resizes. - **overscanCount** (number) - Number of extra rows/columns to render outside the visible area to reduce flickering. - **tagName** (string) - HTML tag name for the root element of the Grid (defaults to 'div'). ``` -------------------------------- ### Grid Component for Virtualized Grids Source: https://context7.com/bvaughn/react-window/llms.txt The Grid component renders virtualized two-dimensional data, mounting only visible cells. It requires specific props for cell and layout configuration and supports ARIA roles for accessibility. ```tsx import { Grid, type CellComponentProps } from "react-window"; type Contact = { name: string; email: string; phone: string; city: string; state: string }; type CellProps = { contacts: Contact[] }; const COLUMNS = ["name", "email", "phone", "city", "state"] as const; function CellComponent({ columnIndex, rowIndex, contacts, style, }: CellComponentProps) { const contact = contacts[rowIndex]; const value = contact[COLUMNS[columnIndex]]; return (
{value}
); } const contacts: Contact[] = Array.from({ length: 10_000 }, (_, i) => ({ name: `Person ${i}`, email: `person${i}@example.com`, phone: "555-0100", city: "Springfield", state: "IL", })); function App() { return (
); } ``` -------------------------------- ### Use `useGridRef` for Typed Grid API Access Source: https://context7.com/bvaughn/react-window/llms.txt Use `useGridRef` to obtain a typed ref for the `Grid` component's imperative API. This allows for direct programmatic scrolling using methods like `scrollToCell`, `scrollToColumn`, and `scrollToRow`. ```tsx import { Grid, useGridRef, type CellComponentProps } from "react-window"; type CellProps = { data: string[][] }; function CellComponent({ columnIndex, rowIndex, data, style }: CellComponentProps) { return
{data[rowIndex]?.[columnIndex]}
; } const data = Array.from({ length: 1000 }, (_, r) => Array.from({ length: 50 }, (_, c) => `R${r}C${c}`) ); function App() { const gridRef = useGridRef(null); function jumpToCell(rowIndex: number, columnIndex: number) { gridRef.current?.scrollToCell({ rowIndex, columnIndex, rowAlign: "center", // "auto" | "center" | "end" | "smart" | "start" columnAlign: "start", behavior: "smooth", }); } function jumpToColumn(index: number) { gridRef.current?.scrollToColumn({ index, align: "start" }); } function jumpToRow(index: number) { gridRef.current?.scrollToRow({ index, align: "center", behavior: "instant" }); } return ( <>
); } ``` -------------------------------- ### Use Dynamic Row Height with useDynamicRowHeight Hook Source: https://context7.com/bvaughn/react-window/llms.txt Use this hook when row heights are not known in advance, such as with text that wraps. It utilizes a ResizeObserver to measure row elements and caches their heights. Ensure no fixed height is set on the row component itself. ```tsx import { List, useDynamicRowHeight, type RowComponentProps } from "react-window"; type RowProps = { paragraphs: string[] }; function RowComponent({ index, paragraphs, style }: RowComponentProps) { return ( // Do NOT set a fixed height here — the ResizeObserver measures the real height
{paragraphs[index]}
); } const paragraphs = [ "Short line.", "A much longer paragraph that will wrap across multiple lines when the container is narrow enough to cause wrapping behavior.", // …thousands more ]; function App() { // Pass a key to reset the cache when the dataset changes const rowHeight = useDynamicRowHeight({ defaultRowHeight: 50, key: "my-dataset" }); return (
); } ``` -------------------------------- ### List with Sticky Children Overlay Source: https://context7.com/bvaughn/react-window/llms.txt Render React nodes as children of the List component to display content above the scrolling rows, such as a sticky header or tooltip. These children are rendered within the list's outer element but outside the virtualized row stack. ```tsx import { List, type RowComponentProps } from "react-window"; type RowProps = object; function RowComponent({ index, style }: RowComponentProps) { return
Row {index}
; } function App() { return (
{/* sticky header sits above all rows */}
Sticky Header
); } ``` -------------------------------- ### List onRowsRendered and onResize Callbacks Source: https://context7.com/bvaughn/react-window/llms.txt Utilize the `onRowsRendered` callback to receive notifications about changes in visible and overscan row index ranges, useful for infinite scrolling or analytics. The `onResize` callback informs about list size changes. ```tsx import { List, type RowComponentProps } from "react-window"; type RowProps = { data: string[] }; function RowComponent({ index, data, style }: RowComponentProps) { return
{data[index]}
; } function App({ data }: { data: string[] }) { return ( { // visible = rows actually in the viewport // all = visible + overscan buffer console.log("Visible rows:", visible.startIndex, "–", visible.stopIndex); console.log("All rendered:", all.startIndex, "–", all.stopIndex); // Trigger data fetch when approaching the end if (visible.stopIndex >= data.length - 20) { fetchMoreData(); } }} onResize={(size, prevSize) => { console.log("List resized from", prevSize, "to", size); }} /> ); } function fetchMoreData() { /* load next page */ } ``` -------------------------------- ### Virtualized Vertical List with Fixed Row Height Source: https://context7.com/bvaughn/react-window/llms.txt Use this component to render a large number of rows with a consistent height. Ensure the parent container has a bounded height for scrolling to function correctly. The `rowComponent` receives `index`, `style`, and any `rowProps` provided. ```tsx import { List, type RowComponentProps } from "react-window"; // 1. Define the extra props your row needs type RowProps = { names: string[] }; // 2. Implement the row component — always spread `style` onto the root element function RowComponent({ index, names, style }: RowComponentProps) { return (
{names[index]} {index + 1} of {names.length}
); } // 3. Render the list — it fills the height of its parent via flexGrow:1 const names = Array.from({ length: 10_000 }, (_, i) => `Item ${i}`); function App() { return ( // Give the list a bounded height so it can scroll
); } ``` -------------------------------- ### useGridCallbackRef Source: https://context7.com/bvaughn/react-window/llms.txt Returns a `[value, setter]` pair so the `GridImperativeAPI` can be accessed as a React state value and shared with other hooks. ```APIDOC ## `useGridCallbackRef` — Ref callback for sharing Grid API Returns a `[value, setter]` pair so the `GridImperativeAPI` can be accessed as a React state value and shared with other hooks. ```tsx import { Grid, useGridCallbackRef, type GridImperativeAPI } from "react-window"; import type { CellComponentProps } from "react-window"; type CellProps = { data: string[][] }; function CellComponent({ columnIndex, rowIndex, data, style }: CellComponentProps) { return
{data[rowIndex]?.[columnIndex]}
; } function useGridActions(grid: GridImperativeAPI | null) { return { goToOrigin: () => grid?.scrollToCell({ rowIndex: 0, columnIndex: 0, behavior: "smooth" }), }; } const data = Array.from({ length: 500 }, (_, r) => Array.from({ length: 20 }, (_, c) => `${r},${c}`) ); function App() { const [grid, setGrid] = useGridCallbackRef(null); const { goToOrigin } = useGridActions(grid); return ( <>
); } ``` ``` -------------------------------- ### useListCallbackRef for Sharing List API Source: https://context7.com/bvaughn/react-window/llms.txt This hook provides a state-backed ref callback for the List component, enabling the imperative API to be read as a state value and shared with other hooks or components. ```tsx import { List, useListCallbackRef, type ListImperativeAPI } from "react-window"; import type { RowComponentProps } from "react-window"; type RowProps = { items: string[] }; function RowComponent({ index, items, style }: RowComponentProps) { return
{items[index]}
; } // A hook that consumes the imperative API function useScrollReset(list: ListImperativeAPI | null) { return () => list?.scrollToRow({ index: 0 }); } const items = Array.from({ length: 1000 }, (_, i) => `Item ${i}`); function App() { // list is the current value; setList is the ref callback passed to const [list, setList] = useListCallbackRef(null); const resetScroll = useScrollReset(list); return ( <>
); } ``` -------------------------------- ### Measure Scrollbar Width with `getScrollbarSize` Source: https://context7.com/bvaughn/react-window/llms.txt Use `getScrollbarSize` to measure the browser's native scrollbar width. This is useful for aligning fixed headers with scrollable content by adjusting padding. ```tsx import { useState } from "react"; import { getScrollbarSize, List, type RowComponentProps } from "react-window"; type Address = { city: string; state: string; zip: string }; type RowProps = { addresses: Address[] }; function RowComponent({ index, addresses, style }: RowComponentProps) { const { city, state, zip } = addresses[index]; return (
{city}
{state}
{zip}
); } const addresses: Address[] = Array.from({ length: 10_000 }, (_, i) => ({ city: `City ${i}`, state: "IL", zip: `6000${i % 10}`, })); function App() { // Measure once at mount time; pass true to re-measure (e.g. after zoom) const [scrollbarWidth] = useState(() => getScrollbarSize()); return (
{/* Fixed header — offset right padding by scrollbar width */}
City
State
Zip
{/* Scrollable list underneath */}
); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.