### Install React Virtualized with npm Source: https://github.com/bvaughn/react-virtualized/blob/master/README.md Use the npm package manager to add react-virtualized as a project dependency. The `--save` flag adds it to the `dependencies` section of your `package.json` file. ```shell npm install react-virtualized --save ``` -------------------------------- ### Include React Virtualized UMD Build in HTML Source: https://github.com/bvaughn/react-virtualized/blob/master/README.md Include the UMD (Universal Module Definition) build and styles directly in your HTML file using `` and ` ``` -------------------------------- ### Rendering Basic React Virtualized Grid (JSX) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/Grid.md Presents a complete basic example of rendering a React Virtualized Grid component. It shows importing necessary libraries (`react`, `react-dom`, `react-virtualized/Grid`), defining sample data, implementing a simple `cellRenderer` function, and using `ReactDOM.render` to mount the Grid into a DOM element with fixed column and row dimensions. This provides a minimal working example for getting started with the Grid. ```jsx import React from 'react'; import ReactDOM from 'react-dom'; import {Grid} from 'react-virtualized'; // Grid data as an array of arrays const list = [ ['Brian Vaughn', 'Software Engineer', 'San Jose', 'CA', 95125 /* ... */], // And so on... ]; function cellRenderer({columnIndex, key, rowIndex, style}) { return (
{list[rowIndex][columnIndex]}
); } // Render your grid ReactDOM.render( , document.getElementById('example'), ); ``` -------------------------------- ### Running Local Demo for react-virtualized Development Source: https://github.com/bvaughn/react-virtualized/blob/master/CONTRIBUTING.md These commands navigate to the project root directory and then use Yarn to start the local development server for the react-virtualized demo application, making it accessible typically at `http://localhost:3001`. ```bash cd yarn start ``` -------------------------------- ### Installing Dependencies for react-virtualized Development Source: https://github.com/bvaughn/react-virtualized/blob/master/CONTRIBUTING.md This command uses Yarn to install or update all necessary project dependencies required for building, testing, and running the react-virtualized project locally. ```bash yarn install ``` -------------------------------- ### Import Components and Styles in JavaScript (ES6/CommonJS) Source: https://github.com/bvaughn/react-virtualized/blob/master/README.md Import the necessary CSS styles once during application bootstrapping. You can import components as named exports from the main package or directly from their CommonJS distribution files for potential bundle size optimization. ```javascript // Most of react-virtualized's styles are functional (eg position, size). // Functional styles are applied directly to DOM elements. // The Table component ships with a few presentational styles as well. // They are optional, but if you want them you will need to also import the CSS file. // This only needs to be done once; probably during your application's bootstrapping process. import 'react-virtualized/styles.css'; // You can import any component you want as a named export from 'react-virtualized', eg import {Column, Table} from 'react-virtualized'; // But if you only use a few react-virtualized components, // And you're concerned about increasing your application's bundle size, // You can directly import only the components you need, like so: import AutoSizer from 'react-virtualized/dist/commonjs/AutoSizer'; import List from 'react-virtualized/dist/commonjs/List'; ``` -------------------------------- ### Rendering Basic React Virtualized Table (JavaScript) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/Table.md Provides a minimal example of rendering a react-virtualized Table component. It sets up a basic data structure, defines columns with fixed widths, and renders the table into a DOM element using ReactDOM.render. Requires react, react-dom, and react-virtualized. ```javascript import React from 'react'; import ReactDOM from 'react-dom'; import {Column, Table} from 'react-virtualized'; import 'react-virtualized/styles.css'; // only needs to be imported once // Table data as an array of objects const list = [ {name: 'Brian Vaughn', description: 'Software engineer'}, // And so on... ]; // Render your table ReactDOM.render( list[index]}>
, document.getElementById('example'), ); ``` -------------------------------- ### Use Component Import with Webpack Alias Source: https://github.com/bvaughn/react-virtualized/blob/master/README.md After configuring the Webpack alias, you can import components using the simplified path. This makes your import statements cleaner while still benefiting from direct module imports. ```javascript import List from 'react-virtualized/List'; ``` -------------------------------- ### Configure Webpack Alias for Direct Imports Source: https://github.com/bvaughn/react-virtualized/blob/master/README.md Configure your Webpack configuration to use aliases, simplifying the import paths for specific components. This allows you to import components like `react-virtualized/List` which Webpack then resolves to the direct ES module path. ```javascript // Partial webpack.config.js { alias: { 'react-virtualized/List': 'react-virtualized/dist/es/List', }, ...rest } ``` -------------------------------- ### Updating Local Master Branch from Upstream in react-virtualized Fork Source: https://github.com/bvaughn/react-virtualized/blob/master/CONTRIBUTING.md These Bash commands are used to ensure your local `master` branch is up-to-date with the latest changes from the original 'upstream' react-virtualized repository before starting work on a new feature or fix. ```bash git checkout master git pull upstream master ``` -------------------------------- ### Rendering React Virtualized Collection (JSX) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/Collection.md This snippet demonstrates a basic implementation of the `react-virtualized` `Collection` component. It imports necessary modules, defines sample data, creates functions for rendering individual cells (`cellRenderer`) and determining their size/position (`cellSizeAndPositionGetter`), and finally renders the `Collection` component to the DOM. It requires React, ReactDOM, and `react-virtualized`. ```JSX import React from 'react'; import ReactDOM from 'react-dom'; import {Collection} from 'react-virtualized'; import 'react-virtualized/styles.css'; // only needs to be imported once // Collection data as an array of objects const list = [ {name: 'Brian Vaughn', x: 13, y: 34, width: 123, height: 234}, // And so on... ]; function cellRenderer({index, key, style}) { return (
{list[index].name}
); } function cellSizeAndPositionGetter({index}) { const datum = list[index]; return { height: datum.height, width: datum.width, x: datum.x, y: datum.y, }; } // Render your grid ReactDOM.render( , document.getElementById('example'), ); ``` -------------------------------- ### Rendering react-virtualized List with AutoSizer Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/AutoSizer.md This example demonstrates how to wrap a `react-virtualized List` component with `AutoSizer`. `AutoSizer` automatically provides the available `height` and `width` to the `List` component via a function child, allowing the list to fill its container. Requires `react`, `react-dom`, `react-virtualized`, and its CSS styles. ```javascript import React from 'react'; import ReactDOM from 'react-dom'; import {AutoSizer, List} from 'react-virtualized'; import 'react-virtualized/styles.css'; // only needs to be imported once // List data as an array of strings const list = [ 'Brian Vaughn', // And so on... ]; function rowRenderer({key, index, style}) { return (
{list[index]}
); } // Render your list ReactDOM.render( {({height, width}) => ( )} , document.getElementById('example'), ); ``` -------------------------------- ### Running react-virtualized v7-to-v8 Rename Codemod (Shell) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/upgrades/Version8.md This shell script automates the renaming of react-virtualized components (FlexColumn, FlexTable, VirtualScroll) using jscodeshift. It requires Node.js (npm), git, and jscodeshift installed globally or locally. The script installs jscodeshift if needed, clones a shallow copy of the react-virtualized repository to access the codemods, runs the specific rename codemod on the specified source directory, and then removes the temporary clone. ```sh cd /path/to/your/project # Install jscodeshift (if you have not already) npm i jscodeshift # Shallow checkout react-virtualized # Codemods aren't stored in NPM (to keep the download small) git clone git@github.com:bvaughn/react-virtualized.git --depth 1 # Run the rename migration on your project's source code jscodeshift -t ./react-virtualized/codemods/7-to-8/rename-components.js ./source # Remove the shallow checkout rm -rf ./react-virtualized ``` -------------------------------- ### Creating react-virtualized v7 Renderer Adapter (JSX) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/upgrades/Version8.md This JSX code provides a helper function, `createCellRenderer`, designed to ease the migration of v7 renderers to v8. Version 8 renderers receive `key` and `style` props which are essential for performance. This function wraps a v7 renderer, applying the new v8 `key` and `style` props to a wrapping `div` element while passing the original v7 props to the wrapped renderer. An example `renderGrid` demonstrates its usage with the `Grid` component. ```jsx // Can be used for Grid, List, or Table function createCellRenderer(cellRenderer) { console.warn('cellRenderer udpate needed'); return function cellRendererWrapper({key, style, ...rest}) { return (
{cellRenderer(rest)}
); }; } // Demonstrates example usage function renderGrid(props) { const {cellRenderer, ...rest} = props; return ; } ``` -------------------------------- ### Rendering Basic react-virtualized List (JavaScript) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/List.md Demonstrates a complete, basic example of rendering a virtualized list using `react-virtualized`. It shows the necessary imports, defines sample list data, provides a simple `rowRenderer` implementation that displays the text content, and renders the `List` component to a DOM element with specified dimensions and properties like `rowCount`, `rowHeight`, and the custom `rowRenderer` function. ```javascript import React from 'react'; import ReactDOM from 'react-dom'; import {List} from 'react-virtualized'; // List data as an array of strings const list = [ 'Brian Vaughn', // And so on... ]; function rowRenderer({ key, // Unique key within array of rows index, // Index of row within collection isScrolling, // The List is currently being scrolled isVisible, // This row is visible within the List (eg it is not an overscanned row) style, // Style object to be applied to row (to position it) }) { return (
{list[index]}
); } // Render your list ReactDOM.render( , document.getElementById('example'), ); ``` -------------------------------- ### Customizing Table Row Renderer with React Sortable Hoc (JSX) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/Table.md Demonstrates how to integrate react-virtualized's Table with react-sortable-hoc by wrapping the default Table and row renderer components. This pattern allows rows to be made sortable while leveraging the virtualized rendering performance. ```jsx import {SortableContainer, SortableElement} from 'react-sortable-hoc'; import {defaultTableRowRenderer, Table} from 'react-virtualized'; const SortableTable = SortableContainer(Table); const SortableTableRowRenderer = SortableElement(defaultTableRowRenderer); function rowRenderer(props) { return ; } function CustomizedTable(props) { return ; } ``` -------------------------------- ### Integrating InfiniteLoader with List (React/JSX) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/InfiniteLoader.md This example demonstrates how to integrate the InfiniteLoader component with react-virtualized's List component to implement infinite scrolling. It defines functions to check if a row is loaded and to fetch more rows from a remote API, rendering the List component within the InfiniteLoader's render prop. ```jsx import React from 'react'; import ReactDOM from 'react-dom'; import { InfiniteLoader, List } from 'react-virtualized'; import 'react-virtualized/styles.css'; // only needs to be imported once // This example assumes you have a way to know/load this information const remoteRowCount const list = []; function isRowLoaded ({ index }) { return !!list[index]; } function loadMoreRows ({ startIndex, stopIndex }) { return fetch(`path/to/api?startIndex=${startIndex}&stopIndex=${stopIndex}`) .then(response => { // Store response data in list... }) } function rowRenderer ({ key, index, style}) { return (
{list[index]}
) } // Render your list ReactDOM.render( {({ onRowsRendered, registerChild }) => ( )} , document.getElementById('example') ); ``` -------------------------------- ### Pass Pass-Thru Props to Trigger Re-renders Source: https://github.com/bvaughn/react-virtualized/blob/master/README.md Since react-virtualized components use `shallowCompare`, changes to data not directly used as props might not trigger a re-render. You can pass an additional prop (like `sortBy` in this example) that changes when the data affecting rendering updates, forcing the component to re-render. ```jsx ``` -------------------------------- ### Updating Masonry Cell Positioner Configuration (JS) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/Masonry.md This example shows how to update the configuration of a previously created cell positioner instance when external conditions change (e.g., window resize). It utilizes the `reset` method on the positioner, passing the new configuration options. After resetting the positioner, it's necessary to call `recomputeCellPositions` on the `Masonry` component instance to trigger a layout recalculation with the new settings. ```javascript cellPositioner.reset({ columnCount: 4, columnWidth: 250, spacer: 15, }); masonryRef.recomputeCellPositions(); ``` -------------------------------- ### Using AutoSizer with ChildComponent Prop (Legacy) Source: https://github.com/bvaughn/react-virtualized/blob/master/CHANGELOG.md This example demonstrates the older syntax for using the AutoSizer component by passing the component to be sized as a ChildComponent prop. This method was deprecated in favor of using the component as a direct child element. ```JSX ``` -------------------------------- ### Rendering List with WindowScroller - JavaScript/JSX Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/WindowScroller.md Basic example showing how to wrap a react-virtualized List component with WindowScroller. It uses the render prop function signature ({ height, isScrolling, onChildScroll, scrollTop }) => element to pass necessary props to the List, enabling scrolling based on the window's scroll position. ```javascript import React from 'react'; import ReactDOM from 'react-dom'; import { List, WindowScroller } from 'react-virtualized'; import 'react-virtualized/styles.css'; // only needs to be imported once ReactDOM.render( {({ height, isScrolling, onChildScroll, scrollTop }) => ( )} , document.getElementById('example') ); ``` -------------------------------- ### Using ScrollSync to Sync Grid and List Scrolling (JSX) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/ScrollSync.md This example demonstrates how to use the ScrollSync component to synchronize the vertical scrolling of a react-virtualized List component with the horizontal scrolling of a Grid component. It passes the `scrollTop` to the List and the `onScroll` handler to the Grid to manage state updates. Required dependencies include react-virtualized and its styles. ```jsx import {Grid, List, ScrollSync} from 'react-virtualized'; import 'react-virtualized/styles.css'; // only needs to be imported once function render(props) { return ( {( clientHeight, clientWidth, onScroll, scrollHeight, scrollLeft, scrollTop, scrollWidth, ) => (
)}
); } ``` -------------------------------- ### Applying react-virtualized v6 to v7 Rename Codemod - Bash Source: https://github.com/bvaughn/react-virtualized/blob/master/CHANGELOG.md This command utilizes the jscodeshift tool to execute a specific codemod script designed to facilitate the migration from react-virtualized version 6 to version 7. The script `rename-properties.js` targets the specified source files or directory and automatically renames properties that were changed in the version 7 API. Ensure jscodeshift is installed and the path to the codemod script is correct. ```bash jscodeshift -t /path/to/react-virtualized/codemods/6-to-7/rename-properties.js source ``` -------------------------------- ### Using WindowScroller with registerChild - JavaScript/JSX Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/WindowScroller.md Example demonstrating how to use the registerChild render prop when the virtualized component (like List) is nested within other elements inside the WindowScroller render prop's return value. The ref={registerChild} is placed on the container element directly wrapping the List, allowing WindowScroller to correctly measure and scroll the list. ```javascript import React from 'react'; import ReactDOM from 'react-dom'; import { List, WindowScroller } from 'react-virtualized'; import 'react-virtualized/styles.css'; // only needs to be imported once ReactDOM.render( {({ height, isScrolling, registerChild, scrollTop }) => (
Table header
)}
, document.getElementById('example') ); ``` -------------------------------- ### Updating react-virtualized Global CSS Class Names (CSS) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/upgrades/Version8.md This CSS snippet shows how global class names used to target react-virtualized components have been updated in version 8. The changes include adding the prefix `_ReactVirtualized___` to all top-level component class names and renaming specific component classes like `FlexTable` to `Table` and `VirtualScroll` to `List`. Custom CSS rules targeting the old class names will need to be updated to reflect the new naming convention. ```css /* before */ .Collection, .FlexTable, .Grid, .VirtualScroll { } /* after */ .ReactVirtualized__Collection, .ReactVirtualized__Grid, .ReactVirtualized__List, .ReactVirtualized__Table { } ``` -------------------------------- ### Using CellMeasurer with Dynamic Image Heights - JSX Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/CellMeasurer.md This configuration sets up a CellMeasurerCache for fixed-width lists with dynamic height. The rowRenderer function uses CellMeasurer's function-child pattern to get measure and registerChild functions. The measure function is triggered by the image's onLoad event, allowing the cell height to be determined after the image has loaded. The renderList function shows how to apply the cache and rowRenderer to the List component. ```jsx import React from 'react'; import { CellMeasurer, CellMeasurerCache, List } from 'react-virtualized'; // In this example, average cell height is assumed to be about 50px. // This value will be used for the initial `Grid` layout. // Width is not dynamic. const cache = new CellMeasurerCache({ defaultHeight: 50, fixedWidth: true }); function rowRenderer ({ index, isScrolling, key, parent, style }) { const source // This comes from your list data return ( {({ measure, registerChild }) => ( // 'style' attribute required to position cell (within parent List)
)}
); } function renderList (props) { return ( ); } ``` -------------------------------- ### Updating react-virtualized Cell Rendering and Styling (JSX) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/upgrades/Version8.md This JSX snippet illustrates the change in how custom styles and class names are applied to cells in react-virtualized v8 compared to v7. In v7 (Before), properties like `cellClassName` and `cellStyle` were set directly on the component (`Grid`). In v8 (After), these props are removed, and the custom class name and style must be applied manually within the cell renderer function itself, typically to the root element returned by the renderer, merging with the required `style` prop provided by the component. ```jsx // Before function renderGrid (props) { return ( (
{list[rowIndex][columnIndex]}
)) } {...props} /> ) } // After function renderGrid (props) { return ( (
{list[rowIndex][columnIndex]}
)) } {...props} /> ) } ``` -------------------------------- ### Running Unit Tests for react-virtualized Development Source: https://github.com/bvaughn/react-virtualized/blob/master/CONTRIBUTING.md These commands navigate to the project root directory and then use Yarn to execute the project's unit tests, which must pass before a pull request is considered for approval. ```bash cd yarn test ``` -------------------------------- ### Cloning and Configuring Fork for react-virtualized Contribution Source: https://github.com/bvaughn/react-virtualized/blob/master/CONTRIBUTING.md This snippet provides the Bash commands needed to fork the react-virtualized repository on GitHub, clone your personal fork locally, navigate into the cloned directory, and add the original repository as an 'upstream' remote for easy syncing. ```bash # Clone your fork of the repo into the current directory git clone https://github.com//react-virtualized # Navigate to the newly cloned directory cd react-virtualized # Assign the original repo to a remote called "upstream" git remote add upstream https://github.com/bvaughn/react-virtualized ``` -------------------------------- ### Pushing Topic Branch to Origin Fork for react-virtualized Contribution Source: https://github.com/bvaughn/react-virtualized/blob/master/CONTRIBUTING.md This Bash command pushes the local topic branch, containing your committed changes, to your personal fork on GitHub ('origin'), making it available for creating a pull request. ```bash git push origin ``` -------------------------------- ### Creating a New Topic Branch for react-virtualized Contribution Source: https://github.com/bvaughn/react-virtualized/blob/master/CONTRIBUTING.md This Bash command creates and switches to a new branch, named ``, based off the current branch (ideally `master`), which is recommended for isolating changes related to a specific feature, change, or fix. ```bash git checkout -b ``` -------------------------------- ### Using ArrowKeyStepper with Grid (JavaScript) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/ArrowKeyStepper.md This snippet demonstrates how to wrap a react-virtualized Grid component with ArrowKeyStepper to enable arrow-key navigation. It shows importing necessary components (React, ReactDOM, ArrowKeyStepper, Grid) and styles, and how the render prop function provided by ArrowKeyStepper passes down required props like `onSectionRendered`, `scrollToColumn`, and `scrollToRow` to the wrapped Grid component. ```javascript import React from 'react'; import ReactDOM from 'react-dom'; import {ArrowKeyStepper, Grid} from 'react-virtualized'; import 'react-virtualized/styles.css'; // only needs to be imported once ReactDOM.render( {({onSectionRendered, scrollToColumn, scrollToRow}) => ( )} , document.getElementById('example'), ); ``` -------------------------------- ### Rendering Basic Masonry Grid with react-virtualized (JSX) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/Masonry.md This snippet demonstrates a basic `Masonry` grid implementation. It initializes a `CellMeasurerCache` with default and fixed dimensions, a `cellPositioner` to define columns and spacing, and a `cellRenderer` function to render individual items. The `Masonry` component is then rendered with these configurations. ```jsx import React from 'react'; import ReactDOM from 'react-dom'; import { CellMeasurer, CellMeasurerCache, createMasonryCellPositioner, Masonry, } from 'react-virtualized'; // Array of images with captions const list = []; // Default sizes help Masonry decide how many images to batch-measure const cache = new CellMeasurerCache({ defaultHeight: 250, defaultWidth: 200, fixedWidth: true, }); // Our masonry layout will use 3 columns with a 10px gutter between const cellPositioner = createMasonryCellPositioner({ cellMeasurerCache: cache, columnCount: 3, columnWidth: 200, spacer: 10, }); function cellRenderer({index, key, parent, style}) { const datum = list[index]; return (

{datum.caption}

); } // Render your grid ReactDOM.render( , document.getElementById('example'), ); ``` -------------------------------- ### Syncing Feature Branch with Upstream Master in react-virtualized Fork Source: https://github.com/bvaughn/react-virtualized/blob/master/CONTRIBUTING.md This command is used to integrate the latest changes from the original 'upstream' `master` branch into your current topic branch, either by merging or rebasing, to keep your work up-to-date and resolve conflicts early. ```bash git pull [--rebase] upstream master ``` -------------------------------- ### Creating Masonry Cell Positioner (JS) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/Masonry.md This snippet demonstrates how to use the built-in `createMasonryCellPositioner` utility function provided by `Masonry`. It requires configuration options such as `cellMeasurerCache`, `columnCount`, `columnWidth`, and an optional `spacer`. The function returns a positioner function that can then be passed to the `Masonry` component's `cellPositioner` prop. It also shows how to capture a reference to the `Masonry` component instance. ```javascript const cellPositioner = createMasonryCellPositioner({ cellMeasurerCache: cache, columnCount: 3, columnWidth: 200, spacer: 10, }); let masonryRef; function renderMasonry(props) { return ( (masonryRef = ref)} {...props} /> ); } ``` -------------------------------- ### Rendering Dynamic Masonry Grid with Image Measurer (JavaScript) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/Masonry.md This snippet shows how to render a `Masonry` grid when item sizes (specifically image dimensions) are not known upfront. It uses the `react-virtualized-image-measurer` library to measure images asynchronously. The `ImageMeasurer` component wraps the `Masonry` component, providing it with item data including measured sizes. ```javascript import React from 'react'; import {render} from 'react-dom'; import { CellMeasurer, CellMeasurerCache, createMasonryCellPositioner, Masonry, } from 'react-virtualized'; import ImageMeasurer from 'react-virtualized-image-measurer'; // Array of images with captions //const list = [{image: 'http://...', title: 'Foo'}]; // We need to make sure images are loaded from scratch every time for this demo const noCacheList = list.map(item => ({ ...item, image: item.image + '?noCache=' + Math.random(), })); const columnWidth = 200; const defaultHeight = 250; const defaultWidth = columnWidth; // Default sizes help Masonry decide how many images to batch-measure const cache = new CellMeasurerCache({ defaultHeight, defaultWidth, fixedWidth: true, }); // Our masonry layout will use 3 columns with a 10px gutter between const cellPositioner = createMasonryCellPositioner({ cellMeasurerCache: cache, columnCount: 3, columnWidth, spacer: 10, }); const MasonryComponent = ({itemsWithSizes}) => { function cellRenderer({index, key, parent, style}) { const {item, size} = itemsWithSizes[index]; const height = columnWidth * (size.height / size.width) || defaultHeight; return (
{item.title}

{item.title}

); } return ( ); }; // Render your grid render( item.image} defaultHeight={defaultHeight} defaultWidth={defaultWidth}> {({itemsWithSizes}) => } , document.getElementById('root'), ); ``` -------------------------------- ### Importing React Virtualized Stylesheet - JavaScript Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/customizingStyles.md This code snippet demonstrates how to import the default CSS stylesheet provided by `react-virtualized`. This is typically done during the application's bootstrapping phase to load the base styles for components. Importing this stylesheet is the first step in enabling the library's default styling before applying any customizations. ```javascript import 'react-virtualized/styles.css'; ``` -------------------------------- ### React-Virtualized React-Lite UMD Compatibility - JavaScript Source: https://github.com/bvaughn/react-virtualized/blob/master/CHANGELOG.md Provides necessary shims for using the react-virtualized library with the UMD build of react-lite. It defines a shallowCompare function on React.addons and sets ReactDOM to React, ensuring compatibility before react-virtualized is loaded. ```JavaScript React.addons = { shallowCompare(context, nextProps, nextState) { return React.PureComponent.prototype.shouldComponentUpdate( nextProps, nextState, ); }, }; ReactDOM = React; ``` -------------------------------- ### Integrating InfiniteLoader with Grid (React/JavaScript) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/InfiniteLoader.md This code snippet shows an approach to integrating InfiniteLoader with the Grid component. It involves wrapping the Grid within a component that manages the InfiniteLoader render prop and maps the Grid's onSectionRendered callback to the onRowsRendered callback required by InfiniteLoader. ```javascript class MyComponent extends Component { constructor (props, context) { super(props, context) this._infiniteLoaderChildFunction = this._infiniteLoaderChildFunction.bind(this) this._onSectionRendered = this._onSectionRendered.bind(this) } render () { const { infiniteLoaderProps } = this.props {this._infiniteLoaderChildFunction} } _infiniteLoaderChildFunction ({ onRowsRendered, registerChild }) { this._onRowsRendered = onRowsRendered const { gridProps } = this.props return ( ) } _onSectionRendered ({ columnStartIndex, columnStopIndex, rowStartIndex, rowStopIndex }) { const startIndex = rowStartIndex * columnCount + columnStartIndex const stopIndex = rowStopIndex * columnCount + columnStopIndex this._onRowsRendered({ startIndex, stopIndex }) } } ``` -------------------------------- ### Defining rowRenderer Function (JSX) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/List.md Explains the `rowRenderer` function signature and its parameters used by `react-virtualized`'s List component. This function is responsible for rendering a single row and must apply the provided `style` object for positioning and sizing, as well as use the unique `key` prop. It also shows how to render a lightweight placeholder while scrolling. ```jsx function rowRenderer({ index, // Index of row isScrolling, // The List is currently being scrolled isVisible, // This row is visible within the List (eg it is not an overscanned row) key, // Unique key within array of rendered rows parent, // Reference to the parent List (instance) style, // Style object to be applied to row (to position it); // This must be passed through to the rendered row element. }) { const user = list[index]; // If row content is complex, consider rendering a light-weight placeholder while scrolling. const content = isScrolling ? '...' : ; // Style is required since it specifies how the row is to be sized and positioned. // React Virtualized depends on this sizing/positioning for proper scrolling behavior. // By default, the List component provides following style properties: // position // left // top // height // width // You can add additional class names or style properties as you would like. // Key is also required by React to more efficiently manage the array of rows. return (
{content}
); } ``` -------------------------------- ### Using AutoSizer with Regular Child Element Source: https://github.com/bvaughn/react-virtualized/blob/master/CHANGELOG.md This snippet illustrates the current, recommended approach for using the AutoSizer component. The component that needs to be sized is placed directly as a child of the AutoSizer component. ```JSX ``` -------------------------------- ### Using ColumnSizer with Grid Component in JavaScript Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/ColumnSizer.md This snippet demonstrates how to wrap a react-virtualized Grid component with the ColumnSizer HOC to enable automatic column width calculation. It shows importing necessary modules, configuring ColumnSizer props like min/max width and total width, and passing the calculated values and ref function from ColumnSizer's render prop to the Grid. ```javascript import React from 'react'; import ReactDOM from 'react-dom'; import {ColumnSizer, Grid} from 'react-virtualized'; import 'react-virtualized/styles.css'; // only needs to be imported once // numColumns, numRows, someCalculatedHeight, and someCalculatedWidth determined here... // Render your list ReactDOM.render( {({adjustedWidth, getColumnWidth, registerChild}) => ( )} , document.getElementById('example'), ); ``` -------------------------------- ### Implementing Infinite-Loading List with React and InfiniteLoader Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/creatingAnInfiniteLoadingList.md This React functional component demonstrates how to create an infinite-loading list using react-virtualized. It takes props indicating the loading state and data, calculates the total row count including a loading indicator row, defines the logic for loading more rows, and determines if a specific row is loaded. It renders either a loading message or the item content based on the row's loading status. This component relies on the InfiniteLoader and List components from react-virtualized. ```jsx function MyComponent({ /** Are there more items to load? (This information comes from the most recent API request.) */ hasNextPage, /** Are we currently loading a page of items? (This may be an in-flight flag in your Redux store for example.) */ isNextPageLoading, /** List of items loaded so far */ list, /** Callback function (eg. Redux action-creator) responsible for loading the next page of items */ loadNextPage, }) { // If there are more items to be loaded then add an extra row to hold a loading indicator. const rowCount = hasNextPage ? list.size + 1 : list.size; // Only load 1 page of items at a time. // Pass an empty callback to InfiniteLoader in case it asks us to load more than once. const loadMoreRows = isNextPageLoading ? () => {} : loadNextPage; // Every row is loaded except for our loading indicator row. const isRowLoaded = ({index}) => !hasNextPage || index < list.size; // Render a list item or a loading indicator. const rowRenderer = ({index, key, style}) => { let content; if (!isRowLoaded({index})) { content = 'Loading...'; } else { content = list.getIn([index, 'name']); } return (
{content}
); }; return ( {({onRowsRendered, registerChild}) => ( )} ); } ``` -------------------------------- ### Rendering Masonry Cell using CellMeasurer (JSX) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/Masonry.md This function demonstrates the required signature and implementation for a `Masonry` cell renderer. It receives parameters like index, scrolling state, a unique key, a parent reference, and a style object. The style object must be applied to the rendered element for correct positioning. It also shows how to wrap the cell's content within a `CellMeasurer` component for dynamic size calculation, passing the required cache, index, key, and parent props. ```jsx function cellRenderer({ index, // Index of item within the collection isScrolling, // The Grid is currently being scrolled key, // Unique key within array of cells parent, // Reference to the parent Grid (instance) style // Style object to be applied to cell (to position it); // This must be passed through to the rendered cell element. }) { return (
{/* Your content goes here */}
); } ``` -------------------------------- ### Importing React Virtualized Styles CSS Source: https://github.com/bvaughn/react-virtualized/blob/master/CHANGELOG.md This snippet shows how to import the required CSS styles for react-virtualized components. As of version 4.0.0, styles were split into a separate stylesheet for better universal/isomorphic use cases and require explicit import. ```JavaScript import 'react-virtualized/styles.css'; ``` -------------------------------- ### Implementing Multi-Column Sorting with createMultiSort in react-virtualized (JSX) Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/multiColumnSortTable.md This snippet demonstrates the basic implementation of multi-column sorting in a react-virtualized Table. It shows how to define a custom sort handler function, create a sortState using createMultiSort, and integrate this state with the Table component and a custom header renderer to display sort indicators based on the multi-sort state. ```jsx import {createTableMultiSort, Column, Table} from 'react-virtualized'; function sort({sortBy, sortDirection}) { // 'sortBy' is an ordered Array of fields. // 'sortDirection' is a map of field name to "ASC" or "DESC" directions. // Sort your collection however you'd like. // When you're done, setState() or update your Flux store, etc. } const sortState = createMultiSort(sort); // When rendering your header columns, // Use the sort state exposed by sortState: const headerRenderer = ({dataKey, label}) => { const showSortIndicator = sortState.sortBy.includes(dataKey); return ( <> {label} {showSortIndicator && ( )} ); }; // Connect sortState to Table by way of the 'sort' prop:
; ``` -------------------------------- ### Rendering MultiGrid Component in React Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/MultiGrid.md This snippet demonstrates how to render a basic MultiGrid component using react-virtualized. It configures the grid with a fixed header row and two fixed columns on the left, defining dimensions and cell rendering logic. ```jsx import {MultiGrid} from 'react-virtualized'; function render() { return ( ); } ``` -------------------------------- ### Implementing Reverse Order List with React Virtualized - JSX Source: https://github.com/bvaughn/react-virtualized/blob/master/docs/reverseList.md This snippet demonstrates a React component using react-virtualized's List to display items in reverse chronological order. New items are added to the beginning of the state array using `unshift`, and an interval is used to simulate data updates. It also shows how to optionally scroll the list to the top (index 0) after adding a new item. ```jsx export default class Example extends Component { constructor(props) { super(props); this.state = { list: [], }; } componentDidMount() { this._interval = setInterval(::this._updateFeed, 500); } componentWillUnmount() { clearInterval(this._interval); } render() { const {list} = this.state; return (
); } _updateFeed() { const list = [...this.state.list]; list .unshift // Add new item here (); this.setState({list}); // If you want to scroll to the top you can do it like this this.refs.List.scrollToRow(0); } _rowRenderer({key, index}) { return (
{/* Your content goes here */}
); } } ```