diff --git a/README.md b/README.md index a93617efb..af5b7e6f9 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ React components for efficiently rendering large lists and tabular data. Check out [the demo](https://bvaughn.github.io/react-virtualized/) for some examples. ### Sponsors + The following wonderful companies have sponsored react-virtualized: @@ -81,13 +82,11 @@ The following wonderful companies have sponsored react-virtualized: -A word about `react-window` ---------------- +## A word about `react-window` If you're considering adding `react-virtualized` to a project, take a look at [`react-window`](https://github.com/bvaughn/react-window) as a possible lighter-weight alternative. [Learn more about how the two libraries compare here.](https://github.com/bvaughn/react-window#how-is-react-window-different-from-react-virtualized) -Getting started ---------------- +## Getting started Install `react-virtualized` using npm. @@ -104,16 +103,16 @@ For example: // 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' +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' +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' +import AutoSizer from 'react-virtualized/dist/commonjs/AutoSizer'; +import List from 'react-virtualized/dist/commonjs/List'; ``` Note webpack 4 makes this optimization itself, see the [documentation](https://webpack.js.org/guides/tree-shaking/#mark-the-file-as-side-effect-free). @@ -131,6 +130,7 @@ If the above syntax looks too cumbersome, or you import react-virtualized compon ``` Then you can just import like so: + ```js import List from 'react-virtualized/List'; @@ -140,15 +140,14 @@ import List from 'react-virtualized/List'; You can also use a global-friendly UMD build: ```html - + ``` Now you're ready to start using the components. You can learn more about which components react-virtualized has to offer [below](#documentation). -Dependencies ---------------- +## Dependencies React Virtualized has very few dependencies and most are managed by NPM automatically. However the following peer dependencies must be specified by your project in order to avoid version conflicts: @@ -156,8 +155,7 @@ However the following peer dependencies must be specified by your project in ord [`react-dom`](https://www.npmjs.com/package/react-dom). NPM will not automatically install these for you but it will show you a warning message with instructions on how to install them. -Pure Components ---------------- +## Pure Components By default all react-virtualized components use [`shallowCompare`](https://facebook.github.io/react/docs/shallow-compare.html) to avoid re-rendering unless props or state has changed. This occasionally confuses users when a collection's data changes (eg `['a','b','c']` => `['d','e','f']`) but props do not (eg `array.length`). @@ -174,10 +172,7 @@ However you can pass through the additional sort property to trigger a re-render For example: ```js - + ``` ###### Public methods @@ -185,78 +180,75 @@ For example: `Grid` and `Collection` components can be forcefully re-rendered using [`forceUpdate`](https://facebook.github.io/react/docs/component-api.html#forceupdate). For `Table` and `List`, you'll need to call [`forceUpdateGrid`](https://github.com/bvaughn/react-virtualized/blob/master/docs/Table.md#forceupdategrid) to ensure that the inner `Grid` is also updated. For `MultiGrid`, you'll need to call [`forceUpdateGrids`](https://github.com/bvaughn/react-virtualized/blob/master/docs/MultiGrid.md#forceupdategrids) to ensure that the inner `Grid`s are updated. -Documentation ---------------- +## Documentation API documentation available [here](docs/README.md). There are also a couple of how-to guides: -* [Customizing classes and styles](docs/customizingStyles.md) -* [Displaying items in reverse order](docs/reverseList.md) -* [Using AutoSizer](docs/usingAutoSizer.md) -* [Creating an infinite-loading list](docs/creatingAnInfiniteLoadingList.md) -* [Natural sort Table](docs/tableWithNaturalSort.md) -* [Sorting a Table by multiple columns](docs/multiColumnSortTable.md) +- [Customizing classes and styles](docs/customizingStyles.md) +- [Displaying items in reverse order](docs/reverseList.md) +- [Using AutoSizer](docs/usingAutoSizer.md) +- [Creating an infinite-loading list](docs/creatingAnInfiniteLoadingList.md) +- [Natural sort Table](docs/tableWithNaturalSort.md) +- [Sorting a Table by multiple columns](docs/multiColumnSortTable.md) -Examples ---------------- +## Examples Examples for each component can be seen in [the documentation](docs/README.md). Here are some online demos of each component: -* [ArrowKeyStepper](https://bvaughn.github.io/react-virtualized/#/components/ArrowKeyStepper) -* [AutoSizer](https://bvaughn.github.io/react-virtualized/#/components/AutoSizer) -* [CellMeasurer](https://bvaughn.github.io/react-virtualized/#/components/CellMeasurer) -* [Collection](https://bvaughn.github.io/react-virtualized/#/components/Collection) -* [ColumnSizer](https://bvaughn.github.io/react-virtualized/#/components/ColumnSizer) -* [Grid](https://bvaughn.github.io/react-virtualized/#/components/Grid) -* [InfiniteLoader](https://bvaughn.github.io/react-virtualized/#/components/InfiniteLoader) -* [List](https://bvaughn.github.io/react-virtualized/#/components/List) -* [Masonry](https://bvaughn.github.io/react-virtualized/#/components/Masonry) -* [MultiGrid](https://bvaughn.github.io/react-virtualized/#/components/MultiGrid) -* [ScrollSync](https://bvaughn.github.io/react-virtualized/#/components/ScrollSync) -* [Table](https://bvaughn.github.io/react-virtualized/#/components/Table) -* [WindowScroller](https://bvaughn.github.io/react-virtualized/#/components/WindowScroller) +- [ArrowKeyStepper](https://bvaughn.github.io/react-virtualized/#/components/ArrowKeyStepper) +- [AutoSizer](https://bvaughn.github.io/react-virtualized/#/components/AutoSizer) +- [CellMeasurer](https://bvaughn.github.io/react-virtualized/#/components/CellMeasurer) +- [Collection](https://bvaughn.github.io/react-virtualized/#/components/Collection) +- [ColumnSizer](https://bvaughn.github.io/react-virtualized/#/components/ColumnSizer) +- [Grid](https://bvaughn.github.io/react-virtualized/#/components/Grid) +- [InfiniteLoader](https://bvaughn.github.io/react-virtualized/#/components/InfiniteLoader) +- [List](https://bvaughn.github.io/react-virtualized/#/components/List) +- [Masonry](https://bvaughn.github.io/react-virtualized/#/components/Masonry) +- [MultiGrid](https://bvaughn.github.io/react-virtualized/#/components/MultiGrid) +- [ScrollSync](https://bvaughn.github.io/react-virtualized/#/components/ScrollSync) +- [Table](https://bvaughn.github.io/react-virtualized/#/components/Table) +- [WindowScroller](https://bvaughn.github.io/react-virtualized/#/components/WindowScroller) And here are some "recipe" type demos: -* [Table with resizable (drag and drop) columns](https://codesandbox.io/s/j30k46l7xw) -* [Collapsable tree view](https://rawgit.com/bvaughn/react-virtualized/master/playground/tree.html) -* [Full-page grid (spreadsheet)](https://rawgit.com/bvaughn/react-virtualized/master/playground/grid.html) -* [Dynamic cell measuring](https://rawgit.com/bvaughn/react-virtualized/master/playground/chat.html) -* [Cell hover effects](https://rawgit.com/bvaughn/react-virtualized/master/playground/hover.html) - -Supported Browsers ---------------- + +- [Table with resizable (drag and drop) columns](https://codesandbox.io/s/j30k46l7xw) +- [Collapsable tree view](https://rawgit.com/bvaughn/react-virtualized/master/playground/tree.html) +- [Full-page grid (spreadsheet)](https://rawgit.com/bvaughn/react-virtualized/master/playground/grid.html) +- [Dynamic cell measuring](https://rawgit.com/bvaughn/react-virtualized/master/playground/chat.html) +- [Cell hover effects](https://rawgit.com/bvaughn/react-virtualized/master/playground/hover.html) + +## Supported Browsers + react-virtualized aims to support all evergreen browsers and recent mobile browsers for iOS and Android. IE 9+ is also supported (although IE 9 will require some user-defined, custom CSS since flexbox layout is not supported). If you find a browser-specific problem, please report it along with a repro case. The easiest way to do this is probably by forking [this Plunker](https://plnkr.co/edit/6syKo8cx3RfoO96hXFT1). -Friends ---------------- +## Friends + Here are some great components built on top of react-virtualized: -* [react-infinite-calendar](https://github.com/clauderic/react-infinite-calendar): Infinite scrolling date-picker with localization, themes, keyboard support, and more -* [react-sortable-hoc](https://github.com/clauderic/react-sortable-hoc): Higher-order components to turn any list into an animated, touch-friendly, sortable list -* [react-sortable-tree](https://github.com/fritz-c/react-sortable-tree): Drag-and-drop sortable representation of hierarchical data -* [react-virtualized-checkbox](https://github.com/emilebres/react-virtualized-checkbox): Checkbox group component with virtualization for large number of options -* [react-virtualized-select](https://github.com/bvaughn/react-virtualized-select): Drop-down menu for React with windowing to support large numbers of options. -* [react-virtualized-tree](https://github.com/diogofcunha/react-virtualized-tree/): A reactive tree component that aims to render large sets of tree structured data in an elegant and performant way -* [react-timeline-9000](https://github.com/BHP-DevHub/react-timeline-9000/): A calendar timeline component that is capable of displaying and interacting with a large number of items -Contributions ------------- +- [react-infinite-calendar](https://github.com/clauderic/react-infinite-calendar): Infinite scrolling date-picker with localization, themes, keyboard support, and more +- [react-sortable-hoc](https://github.com/clauderic/react-sortable-hoc): Higher-order components to turn any list into an animated, touch-friendly, sortable list +- [react-sortable-tree](https://github.com/fritz-c/react-sortable-tree): Drag-and-drop sortable representation of hierarchical data +- [react-virtualized-checkbox](https://github.com/emilebres/react-virtualized-checkbox): Checkbox group component with virtualization for large number of options +- [react-virtualized-select](https://github.com/bvaughn/react-virtualized-select): Drop-down menu for React with windowing to support large numbers of options. +- [react-virtualized-tree](https://github.com/diogofcunha/react-virtualized-tree/): A reactive tree component that aims to render large sets of tree structured data in an elegant and performant way +- [react-timeline-9000](https://github.com/BHP-DevHub/react-timeline-9000/): A calendar timeline component that is capable of displaying and interacting with a large number of items + +## Contributions Use [GitHub issues](https://github.com/bvaughn/react-virtualized/issues) for requests. I actively welcome pull requests; learn how to [contribute](https://github.com/bvaughn/react-virtualized/blob/master/CONTRIBUTING.md). -Changelog ---------- +## Changelog Changes are tracked in the [changelog](https://github.com/bvaughn/react-virtualized/blob/master/CHANGELOG.md). -License ---------- +## License -*react-virtualized* is available under the MIT License. +_react-virtualized_ is available under the MIT License. diff --git a/docs/ArrowKeyStepper.md b/docs/ArrowKeyStepper.md index 9421b3e86..4c9083098 100644 --- a/docs/ArrowKeyStepper.md +++ b/docs/ArrowKeyStepper.md @@ -1,5 +1,4 @@ -ArrowKeyStepper ---------------- +## ArrowKeyStepper High-order component that decorates another virtualized component and responds to arrow-key events by scrolling one row or column at a time. This provides a snap-to behavior rather than the default browser scrolling behavior. @@ -8,33 +7,35 @@ Note that unlike the other HOCs in react-virtualized, the `ArrowKeyStepper` adds The appearance of this wrapper element can be customized using the `className` property. ### Prop Types -| Property | Type | Required? | Description | -|:---|:---|:---:|:---| -| children | Function | ✓ | Function responsible for rendering children. This function should implement the following signature: `({ onSectionRendered: Function, scrollToColumn: number, scrollToRow: number }) => PropTypes.element` | -| className | String | | CSS class name to attach to the wrapper `
`. | -| columnCount | Number | ✓ | Number of columns in grid; for `Table` and `List` this property should always be `1`. | -| disabled | Boolean | | Disables all scrolling using arrow-keys; defaults to `false` | -| isControlled | Boolean | | This component is "controlled"; it will not update `scrollToColumn` or `scrollToRow`. This property should be used with `onScrollToChange`. | -| mode | "edges" or "cells" | | Controls behavior of stepper when arrow key direction changes. "cells" means that the index will only increment or decrement by 1; "edges" (default) means that the opposite side of the grid will be incremented. | -| onScrollToChange | Function | | Called when arrow key navigation should update the current scroll-to values. | -| rowCount | Number | ✓ | Number of rows in grid. | -| scrollToColumn | Number | | Optional default/initial `scrollToColumn` value | -| scrollToRow | Number | | Optional default/initial `scrollToRow` value | + +| Property | Type | Required? | Description | +| :--------------- | :----------------- | :-------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| children | Function | ✓ | Function responsible for rendering children. This function should implement the following signature: `({ onSectionRendered: Function, scrollToColumn: number, scrollToRow: number }) => PropTypes.element` | +| className | String | | CSS class name to attach to the wrapper `
`. | +| columnCount | Number | ✓ | Number of columns in grid; for `Table` and `List` this property should always be `1`. | +| disabled | Boolean | | Disables all scrolling using arrow-keys; defaults to `false` | +| isControlled | Boolean | | This component is "controlled"; it will not update `scrollToColumn` or `scrollToRow`. This property should be used with `onScrollToChange`. | +| mode | "edges" or "cells" | | Controls behavior of stepper when arrow key direction changes. "cells" means that the index will only increment or decrement by 1; "edges" (default) means that the opposite side of the grid will be incremented. | +| onScrollToChange | Function | | Called when arrow key navigation should update the current scroll-to values. | +| rowCount | Number | ✓ | Number of rows in grid. | +| scrollToColumn | Number | | Optional default/initial `scrollToColumn` value | +| scrollToRow | Number | | Optional default/initial `scrollToRow` value | ### Public Methods ##### setScrollIndexes ({ scrollToColumn: number, scrollToRow: number }) + Override the local state of the component with new values for `scrollToRow` and `scrollToColumn`. ### Children function The child function is passed the following named parameters: -| Parameter | Type | Description | -|:---|:---|:---| +| Parameter | Type | Description | +| :---------------- | :------- | :--------------------------------------------------------------------------------------------------------------------------- | | onSectionRendered | Function | Pass-through callback to be attached to child component; informs the key-stepper which range of cells are currently visible. | -| scrollToColumn | Number | Specifies which column in the child component should be visible | -| scrollToRow | Number | Specifies which row in the child component should be visible | +| scrollToColumn | Number | Specifies which column in the child component should be visible | +| scrollToRow | Number | Specifies which row in the child component should be visible | ### Examples @@ -43,15 +44,12 @@ You can decorate any virtualized component (eg. `Table`, `Grid`, or `List`) with ```javascript import React from 'react'; import ReactDOM from 'react-dom'; -import { ArrowKeyStepper, Grid } from 'react-virtualized'; +import {ArrowKeyStepper, Grid} from 'react-virtualized'; import 'react-virtualized/styles.css'; // only needs to be imported once ReactDOM.render( - - {({ onSectionRendered, scrollToColumn, scrollToRow }) => ( + + {({onSectionRendered, scrollToColumn, scrollToRow}) => ( )} , - document.getElementById('example') + document.getElementById('example'), ); ``` diff --git a/docs/AutoSizer.md b/docs/AutoSizer.md index ad09e8ece..ff7350aad 100644 --- a/docs/AutoSizer.md +++ b/docs/AutoSizer.md @@ -1,20 +1,20 @@ -AutoSizer ---------------- +## AutoSizer High-order component that automatically adjusts the width and height of a single child. ### Prop Types -| Property | Type | Required? | Description | -|:---|:---|:---:|:---| -| children | Function | ✓ | Function responsible for rendering children. This function should implement the following signature: `({ height: number, width: number }) => PropTypes.element` | -| className | String | | Optional custom CSS class name to attach to root `AutoSizer` element. This is an advanced property and is not typically necessary. | -| defaultHeight | Number | | Height passed to child for initial render; useful for server-side rendering. This value will be overridden with an accurate height after mounting. | -| defaultWidth | Number | | Width passed to child for initial render; useful for server-side rendering. This value will be overridden with an accurate width after mounting. | -| disableHeight | Boolean | | Fixed `height`; if specified, the child's `height` property will not be managed | -| disableWidth | Boolean | | Fixed `width`; if specified, the child's `width` property will not be managed | -| nonce | String | | Nonce of the inlined stylesheets for [Content Security Policy](https://www.w3.org/TR/2016/REC-CSP2-20161215/#script-src-the-nonce-attribute) | -| onResize | Function | | Callback to be invoked on-resize; it is passed the following named parameters: `({ height: number, width: number })`. | -| style | Object | | Optional custom inline style to attach to root `AutoSizer` element. This is an advanced property and is not typically necessary. | + +| Property | Type | Required? | Description | +| :------------ | :------- | :-------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| children | Function | ✓ | Function responsible for rendering children. This function should implement the following signature: `({ height: number, width: number }) => PropTypes.element` | +| className | String | | Optional custom CSS class name to attach to root `AutoSizer` element. This is an advanced property and is not typically necessary. | +| defaultHeight | Number | | Height passed to child for initial render; useful for server-side rendering. This value will be overridden with an accurate height after mounting. | +| defaultWidth | Number | | Width passed to child for initial render; useful for server-side rendering. This value will be overridden with an accurate width after mounting. | +| disableHeight | Boolean | | Fixed `height`; if specified, the child's `height` property will not be managed | +| disableWidth | Boolean | | Fixed `width`; if specified, the child's `width` property will not be managed | +| nonce | String | | Nonce of the inlined stylesheets for [Content Security Policy](https://www.w3.org/TR/2016/REC-CSP2-20161215/#script-src-the-nonce-attribute) | +| onResize | Function | | Callback to be invoked on-resize; it is passed the following named parameters: `({ height: number, width: number })`. | +| style | Object | | Optional custom inline style to attach to root `AutoSizer` element. This is an advanced property and is not typically necessary. | ### Examples @@ -30,30 +30,27 @@ Read more about common `AutoSizer` questions [here](usingAutoSizer.md). ```javascript import React from 'react'; import ReactDOM from 'react-dom'; -import { AutoSizer, List } from 'react-virtualized'; +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' + 'Brian Vaughn', // And so on... ]; -function rowRenderer ({ key, index, style }) { +function rowRenderer({key, index, style}) { return ( -
+
{list[index]}
- ) + ); } // Render your list ReactDOM.render( - {({ height, width }) => ( + {({height, width}) => ( )} , - document.getElementById('example') + document.getElementById('example'), ); ``` diff --git a/docs/CellMeasurer.md b/docs/CellMeasurer.md index 024cc3468..d50fc5c9b 100644 --- a/docs/CellMeasurer.md +++ b/docs/CellMeasurer.md @@ -1,5 +1,4 @@ -CellMeasurer ---------------- +## CellMeasurer High-order component that automatically measures a cell's contents by temporarily rendering it in a way that is not visible to the user. Specify a fixed width to measure dynamic height (or vice versa). @@ -9,13 +8,14 @@ This is an advanced component and has some limitations and performance considera `CellMeasurer` can be used with `Grid`, `List`, and `Table` components. It is not intended to be used with the `Collection` component. ### Prop Types -| Property | Type | Required? | Description | -|:---|:---|:---:|:---| -| cache | `CellMeasurerCache` | ✓ | Cache to be shared between `CellMeasurer` and its parent `Grid`. Learn more [here](#cellmeasurercache). | -| children | Element or Function | ✓ | Either a React element as a child (eg `
`) or a function (eg. `({ measure }) =>
`). See [below](#using-cellmeasurer-with-images) for more detailed examples. | -| columnIndex | number | ✓ | Index of column being measured (within the parent `Grid`) or 0 (if used within a `List` or `Table`). | -| parent | `Grid` | ✓ | Reference to the parent `Grid`; this value is passed by `Grid` to the `cellRenderer` and should be passed along as-is. | -| rowIndex | number | ✓ | Index of row being measured (within the parent `Grid`). | + +| Property | Type | Required? | Description | +| :---------- | :------------------ | :-------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| cache | `CellMeasurerCache` | ✓ | Cache to be shared between `CellMeasurer` and its parent `Grid`. Learn more [here](#cellmeasurercache). | +| children | Element or Function | ✓ | Either a React element as a child (eg `
`) or a function (eg. `({ measure }) =>
`). See [below](#using-cellmeasurer-with-images) for more detailed examples. | +| columnIndex | number | ✓ | Index of column being measured (within the parent `Grid`) or 0 (if used within a `List` or `Table`). | +| parent | `Grid` | ✓ | Reference to the parent `Grid`; this value is passed by `Grid` to the `cellRenderer` and should be passed along as-is. | +| rowIndex | number | ✓ | Index of row being measured (within the parent `Grid`). | ### CellMeasurerCache @@ -23,15 +23,16 @@ The `CellMeasurerCache` stores `CellMeasurer` measurements and shares them with It should be configured based on the type of measurements you need. It accepts the following parameters: ### Prop Types -| Property | Type | Required? | Description | -|:---|:---|:---:|:---| -| defaultHeight | number | | Unmeasured cells will initially report this height | -| defaultWidth | number | | Unmeasured cells will initially report this width | -| fixedHeight | boolean | | Rendered cells will have a fixed height, dynamic width | -| fixedWidth | boolean | | Rendered cells will have a fixed width, dynamic height | -| minHeight | number | | Derived row height (of multiple cells) should not be less than this value | -| minWidth | number | | Derived column width (of multiple cells) should not be less than this value | -| keyMapper | KeyMapper | | Enables more intelligent mapping of a given column and row index to an item ID. This prevents a cell cache from being invalidated when its parent collection is modified. `(rowIndex: number, columnIndex: number) => any` | + +| Property | Type | Required? | Description | +| :------------ | :-------- | :-------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| defaultHeight | number | | Unmeasured cells will initially report this height | +| defaultWidth | number | | Unmeasured cells will initially report this width | +| fixedHeight | boolean | | Rendered cells will have a fixed height, dynamic width | +| fixedWidth | boolean | | Rendered cells will have a fixed width, dynamic height | +| minHeight | number | | Derived row height (of multiple cells) should not be less than this value | +| minWidth | number | | Derived column width (of multiple cells) should not be less than this value | +| keyMapper | KeyMapper | | Enables more intelligent mapping of a given column and row index to an item ID. This prevents a cell cache from being invalidated when its parent collection is modified. `(rowIndex: number, columnIndex: number) => any` | Note that while all of the individual parameters above are optional, you must supply at least some of them. `CellMeasurerCache` is not meant to measure cells that are both dynamic width _and_ height. @@ -41,11 +42,13 @@ See [below](#limitations-and-performance-considerations) for more information. ### `CellMeasurerCache` Public Methods ##### clear (rowIndex: number, columnIndex: number) + Reset cached measurements for a specific cell. This should be called when a cell needs to be re-measured to handle dynamic content (eg. replacing a loading indicator with loaded content or reacting to state-changes for stateful cells). ##### clearAll () + Reset cached measurements for all cells. This method should be called when a `Grid`, `List` or `Table` needs to reflow content due to a resizing event for a responsive layout (eg. a window width resize may have an impact on the height of cells). diff --git a/docs/Collection.md b/docs/Collection.md index 7e69d0802..2b292516c 100644 --- a/docs/Collection.md +++ b/docs/Collection.md @@ -1,5 +1,4 @@ -Collection ---------------- +## Collection Renders scattered or non-linear data. Unlike `Grid`, which renders checkerboard data, `Collection` can render arbitrarily positioned- even overlapping- data. @@ -7,28 +6,29 @@ Unlike `Grid`, which renders checkerboard data, `Collection` can render arbitrar **Note** that this component's measuring and layout phase is more expensive than `Grid` since it can not assume a correlation between a cell's index and position. For this reason it will take significantly longer to initialize than the more linear/checkerboard components. ### Prop Types -| Property | Type | Required? | Description | -|:---|:---|:---:|:---| -| autoHeight | Boolean | | Outer `height` of `Collection` is set to "auto". This property should only be used in conjunction with the `WindowScroller` HOC. | -| className | String | | Optional custom CSS class name to attach to root `Collection` element. | -| cellCount | Number | ✓ | Number of cells in collection. | -| cellGroupRenderer | Function | | Responsible for rendering a group of cells given their indices.: `({ cellSizeAndPositionGetter:Function, indices: Array, cellRenderer: Function }): Array` | -| cellRenderer | Function | ✓ | Responsible for rendering a cell given an row and column index: `({ index: number, isScrolling: boolean, key: string, style: object }): PropTypes.element` | -| cellSizeAndPositionGetter | Function | ✓ | Callback responsible for returning size and offset/position information for a given cell (index): `({ index: number }): { height: number, width: number, x: number, y: number }` | -| height | Number | ✓ | Height of Collection; this property determines the number of visible (vs virtualized) rows. | -| horizontalOverscanSize | Number | | Enables the `Collection` to horizontally "overscan" its content similar to how `Grid` does. This can reduce flicker around the edges when a user scrolls quickly. This property defaults to `0`; | -| id | String | | Optional custom id to attach to root `Collection` element. | -| noContentRenderer | Function | | Optional renderer to be rendered inside the grid when `cellCount` is 0: `(): PropTypes.node` | -| onSectionRendered | Function | | Callback invoked with information about the section of the Collection that was just rendered: `({ indices: Array }): void` | -| onScroll | Function | | Callback invoked whenever the scroll offset changes within the inner scrollable region: `({ clientHeight: number, clientWidth: number, scrollHeight: number, scrollLeft: number, scrollTop: number, scrollWidth: number }): void` | -| scrollLeft | Number | | Horizontal offset | -| scrollToAlignment | String | | Controls the alignment of scrolled-to-cells. The default ("_auto_") scrolls the least amount possible to ensure that the specified cell is fully visible. Use "_start_" to always align cells to the top/left of the `Collection` and "_end_" to align them bottom/right. Use "_center_" to align specified cell in the middle of container. | -| scrollToCell | Number | | Cell index to ensure visible (by scrolling if necessary) | -| scrollTop | Number | | Vertical offset | -| sectionSize | Number | | Optionally override the size of the sections a Collection's cells are split into. This is an advanced option and should only be used for performance tuning purposes. | -| style | Object | | Optional custom inline style to attach to root Collection element. | -| verticalOverscanSize | Number | | Enables the `Collection` to vertically "overscan" its content similar to how `Grid` does. This can reduce flicker around the edges when a user scrolls quickly. This property defaults to `0`; | -| width | Number | ✓ | Width of Collection; this property determines the number of visible (vs virtualized) columns. | + +| Property | Type | Required? | Description | +| :------------------------ | :------- | :-------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| autoHeight | Boolean | | Outer `height` of `Collection` is set to "auto". This property should only be used in conjunction with the `WindowScroller` HOC. | +| className | String | | Optional custom CSS class name to attach to root `Collection` element. | +| cellCount | Number | ✓ | Number of cells in collection. | +| cellGroupRenderer | Function | | Responsible for rendering a group of cells given their indices.: `({ cellSizeAndPositionGetter:Function, indices: Array, cellRenderer: Function }): Array` | +| cellRenderer | Function | ✓ | Responsible for rendering a cell given an row and column index: `({ index: number, isScrolling: boolean, key: string, style: object }): PropTypes.element` | +| cellSizeAndPositionGetter | Function | ✓ | Callback responsible for returning size and offset/position information for a given cell (index): `({ index: number }): { height: number, width: number, x: number, y: number }` | +| height | Number | ✓ | Height of Collection; this property determines the number of visible (vs virtualized) rows. | +| horizontalOverscanSize | Number | | Enables the `Collection` to horizontally "overscan" its content similar to how `Grid` does. This can reduce flicker around the edges when a user scrolls quickly. This property defaults to `0`; | +| id | String | | Optional custom id to attach to root `Collection` element. | +| noContentRenderer | Function | | Optional renderer to be rendered inside the grid when `cellCount` is 0: `(): PropTypes.node` | +| onSectionRendered | Function | | Callback invoked with information about the section of the Collection that was just rendered: `({ indices: Array }): void` | +| onScroll | Function | | Callback invoked whenever the scroll offset changes within the inner scrollable region: `({ clientHeight: number, clientWidth: number, scrollHeight: number, scrollLeft: number, scrollTop: number, scrollWidth: number }): void` | +| scrollLeft | Number | | Horizontal offset | +| scrollToAlignment | String | | Controls the alignment of scrolled-to-cells. The default ("_auto_") scrolls the least amount possible to ensure that the specified cell is fully visible. Use "_start_" to always align cells to the top/left of the `Collection` and "_end_" to align them bottom/right. Use "_center_" to align specified cell in the middle of container. | +| scrollToCell | Number | | Cell index to ensure visible (by scrolling if necessary) | +| scrollTop | Number | | Vertical offset | +| sectionSize | Number | | Optionally override the size of the sections a Collection's cells are split into. This is an advanced option and should only be used for performance tuning purposes. | +| style | Object | | Optional custom inline style to attach to root Collection element. | +| verticalOverscanSize | Number | | Enables the `Collection` to vertically "overscan" its content similar to how `Grid` does. This can reduce flicker around the edges when a user scrolls quickly. This property defaults to `0`; | +| width | Number | ✓ | Width of Collection; this property determines the number of visible (vs virtualized) columns. | ### Public Methods @@ -43,10 +43,10 @@ Since Collection only receives `cellCount` (and not the underlying List or Array The Collection component supports the following static class names -| Property | Description | -|:---|:---| -| ReactVirtualized__Collection | Main (outer) element | -| ReactVirtualized__Collection__innerScrollContainer | Inner scrollable area | +| Property | Description | +| :------------------------------------------------- | :-------------------- | +| ReactVirtualized\_\_Collection | Main (outer) element | +| ReactVirtualized**Collection**innerScrollContainer | Inner scrollable area | ### Examples @@ -56,35 +56,32 @@ Below is a very basic `Collection` example. It displays an array of objects with ```jsx import React from 'react'; import ReactDOM from 'react-dom'; -import { Collection } from 'react-virtualized'; +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 } + {name: 'Brian Vaughn', x: 13, y: 34, width: 123, height: 234}, // And so on... ]; -function cellRenderer ({ index, key, style }) { +function cellRenderer({index, key, style}) { return ( -
+
{list[index].name}
- ) + ); } -function cellSizeAndPositionGetter ({ index }) { - const datum = list[index] +function cellSizeAndPositionGetter({index}) { + const datum = list[index]; return { height: datum.height, width: datum.width, x: datum.x, - y: datum.y - } + y: datum.y, + }; } // Render your grid @@ -96,6 +93,6 @@ ReactDOM.render( height={300} width={300} />, - document.getElementById('example') + document.getElementById('example'), ); ``` diff --git a/docs/Column.md b/docs/Column.md index 98ad711cb..195f4fe07 100644 --- a/docs/Column.md +++ b/docs/Column.md @@ -1,29 +1,29 @@ -Column ---------------- +## Column Describes the header and cell contents of a table column. #### Prop Types -| Property | Type | Required? | Description | -|:---|:---|:---:|:---| -| cellDataGetter | Function | | Callback responsible for returning a cell's data, given its `dataKey`. [Learn more](#celldatagetter) | -| cellRenderer | Function | | Callback responsible for rendering a cell's contents. [Learn more](#cellrenderer) | -| className | String | | CSS class to apply to rendered cell container | -| columnData | Object | | Additional data passed to this column's `cellDataGetter`. Use this object to relay action-creators or relational data. | -| dataKey | any | ✓ | Uniquely identifies the row-data attribute corresponding to this cell (eg this might be "name" in an array of user objects). | -| defaultSortDirection| [SortDirection](SortDirection.md) | | Default sort order when clicked for the first time. Valid options include "ASC" and "DESC". Defaults to "ASC" | -| disableSort | Boolean | | If sort is enabled for the table at large, disable it for this column | -| flexGrow | Number | | Flex grow style; defaults to 0 | -| flexShrink | Number | | Flex shrink style; defaults to 1 | -| headerClassName | String | | CSS class to apply to this column's header | -| headerRenderer | Function | | Optional callback responsible for rendering a column's header column. [Learn more](#headerrenderer) | -| headerStyle | Object | | Optional inline style to apply to this column's header | -| id | String | | Optional id to set on the column header; used for [`aria-describedby`](https://www.w3.org/TR/wai-aria/states_and_properties#aria-describedby) | -| label | Node | | Header label for this column | -| maxWidth | Number | | Maximum width of column; this property will only be used if :flexGrow is greater than 0 | -| minWidth | Number | | Minimum width of column | -| style | Object | | Optional inline style to apply to rendered cell container | -| width | Number | ✓ | Flex basis (width) for this column; This value can grow or shrink based on `flexGrow` and `flexShrink` properties | + +| Property | Type | Required? | Description | +| :------------------- | :-------------------------------- | :-------: | :-------------------------------------------------------------------------------------------------------------------------------------------- | +| cellDataGetter | Function | | Callback responsible for returning a cell's data, given its `dataKey`. [Learn more](#celldatagetter) | +| cellRenderer | Function | | Callback responsible for rendering a cell's contents. [Learn more](#cellrenderer) | +| className | String | | CSS class to apply to rendered cell container | +| columnData | Object | | Additional data passed to this column's `cellDataGetter`. Use this object to relay action-creators or relational data. | +| dataKey | any | ✓ | Uniquely identifies the row-data attribute corresponding to this cell (eg this might be "name" in an array of user objects). | +| defaultSortDirection | [SortDirection](SortDirection.md) | | Default sort order when clicked for the first time. Valid options include "ASC" and "DESC". Defaults to "ASC" | +| disableSort | Boolean | | If sort is enabled for the table at large, disable it for this column | +| flexGrow | Number | | Flex grow style; defaults to 0 | +| flexShrink | Number | | Flex shrink style; defaults to 1 | +| headerClassName | String | | CSS class to apply to this column's header | +| headerRenderer | Function | | Optional callback responsible for rendering a column's header column. [Learn more](#headerrenderer) | +| headerStyle | Object | | Optional inline style to apply to this column's header | +| id | String | | Optional id to set on the column header; used for [`aria-describedby`](https://www.w3.org/TR/wai-aria/states_and_properties#aria-describedby) | +| label | Node | | Header label for this column | +| maxWidth | Number | | Maximum width of column; this property will only be used if :flexGrow is greater than 0 | +| minWidth | Number | | Minimum width of column | +| style | Object | | Optional inline style to apply to rendered cell container | +| width | Number | ✓ | Flex basis (width) for this column; This value can grow or shrink based on `flexGrow` and `flexShrink` properties | #### cellDataGetter diff --git a/docs/ColumnSizer.md b/docs/ColumnSizer.md index be869fdf5..010879cba 100644 --- a/docs/ColumnSizer.md +++ b/docs/ColumnSizer.md @@ -1,26 +1,26 @@ -ColumnSizer ---------------- +## ColumnSizer High-order component that auto-calculates column-widths for `Grid` cells. ### Prop Types -| Property | Type | Required? | Description | -|:---|:---|:---:|:---| -| children | Function | ✓ | Function responsible for rendering a virtualized Grid. This function should implement the following signature: `({ adjustedWidth: number, getColumnWidth: Function, registerChild: Function }) => PropTypes.element` | -| columnMaxWidth | Number | | Optional maximum allowed column width | -| columnMinWidth | Number | | Optional minimum allowed column width | -| width | Number | ✓ | Width of Grid or `Table` child | + +| Property | Type | Required? | Description | +| :------------- | :------- | :-------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| children | Function | ✓ | Function responsible for rendering a virtualized Grid. This function should implement the following signature: `({ adjustedWidth: number, getColumnWidth: Function, registerChild: Function }) => PropTypes.element` | +| columnMaxWidth | Number | | Optional maximum allowed column width | +| columnMinWidth | Number | | Optional minimum allowed column width | +| width | Number | ✓ | Width of Grid or `Table` child | ### Children function The child function is passed the following named parameters: -| Parameter | Type | Description | -|:---|:---|:---| -| adjustedWidth | Number | This number reflects the lesser of the overall `Grid` width or the width of all columns. Use this to make your `Grid` shrink to fit sparse content. | -| columnWidth | Number | This value should be passed to the `Grid`'s `columnWidth` property. | +| Parameter | Type | Description | +| :------------- | :------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| adjustedWidth | Number | This number reflects the lesser of the overall `Grid` width or the width of all columns. Use this to make your `Grid` shrink to fit sparse content. | +| columnWidth | Number | This value should be passed to the `Grid`'s `columnWidth` property. | | getColumnWidth | Function | This value can be passed to the `Grid`'s `columnWidth` property but it's recommended that you use the `columnWidth` property instead. This is a legacy property. | -| registerChild | Function | This function should be set as the child's `ref` property. It enables a set of rows to be refreshed once their data has finished loading. | +| registerChild | Function | This function should be set as the child's `ref` property. It enables a set of rows to be refreshed once their data has finished loading. | ### Examples @@ -29,7 +29,7 @@ This example displays a `Grid` that shrinks to fit sparse content (using the `ad ```javascript import React from 'react'; import ReactDOM from 'react-dom'; -import { ColumnSizer, Grid } from 'react-virtualized'; +import {ColumnSizer, Grid} from 'react-virtualized'; import 'react-virtualized/styles.css'; // only needs to be imported once // numColumns, numRows, someCalculatedHeight, and someCalculatedWidth determined here... @@ -40,9 +40,8 @@ ReactDOM.render( columnMaxWidth={100} columnMinWidth={50} columnCount={numColumns} - width={someCalculatedWidth} - > - {({ adjustedWidth, getColumnWidth, registerChild }) => ( + width={someCalculatedWidth}> + {({adjustedWidth, getColumnWidth, registerChild}) => ( )} , - document.getElementById('example') + document.getElementById('example'), ); ``` diff --git a/docs/Grid.md b/docs/Grid.md index 7a7b54eef..20bec32e2 100644 --- a/docs/Grid.md +++ b/docs/Grid.md @@ -1,48 +1,48 @@ -Grid ---------------- +## Grid A windowed grid of elements. `Grid` only renders cells necessary to fill itself based on the current horizontal and vertical scroll position. A simple `Grid` example can be seen [here](#basic-grid-example). ### Prop Types -| Property | Type | Required? | Description | -|:---|:---|:---:|:---| -| autoContainerWidth | Boolean | | Set the width of the inner scrollable container to 'auto'. This is useful for single-column Grids to ensure that the column doesn't extend below a vertical scrollbar. | -| autoHeight | Boolean | | Outer `height` of `Grid` is set to "auto". This property should only be used in conjunction with the `WindowScroller` HOC. | -| autoWidth | Boolean | | Outer `width` of `Grid` is set to "auto". This property should only be used in conjunction with the `WindowScroller` HOC. | -| cellRangeRenderer | Function | | Responsible for rendering a group of cells given their index ranges. [Learn more](#cellrangerenderer) | -| cellRenderer | Function | ✓ | Responsible for rendering a cell given an row and column index. [Learn more](#cellrenderer) | -| className | String | | Optional custom CSS class name to attach to root `Grid` element. | -| columnCount | Number | ✓ | Number of columns in grid. | -| columnWidth | Number or Function | ✓ | Either a fixed column width (number) or a function that returns the width of a column given its index: `({ index: number }): number`. If function is used, specify `estimatedColumnSize` for more consistent scrolling behavior. | -| containerProps | Object | | Responsible for adding props to the cell-container, i.e. `onWheel`. -| containerRole | string | | ARIA role for the cell-container; defaults to "rowgroup" | -| containerStyle | Object | | Optional custom inline style to attach to inner cell-container element. | -| deferredMeasurementCache | `CellMeasurer` | | If CellMeasurer is used to measure this Grid's children, this should be a pointer to its CellMeasurerCache. A shared CellMeasurerCache reference enables Grid and CellMeasurer to share measurement data. | -| estimatedColumnSize | Number | | Used to estimate the total width of a `Grid` before all of its columns have actually been measured. The estimated total width is adjusted as columns are rendered. | -| estimatedRowSize | Number | | Used to estimate the total height of a `Grid` before all of its rows have actually been measured. The estimated total height is adjusted as rows are rendered. | -| height | Number | ✓ | Height of Grid; this property determines the number of visible (vs virtualized) rows. | -| id | String | | Optional custom id to attach to root `Grid` element. | -| isScrolling | Boolean | | Override internal is-scrolling state tracking. This property is primarily intended for use with the WindowScroller component. | -| isScrollingOptOut | Boolean | | Prevents re-rendering of visible cells on scroll end. | -| noContentRenderer | Function | | Optional renderer to be rendered inside the grid when either `rowCount` or `columnCount` is empty: `(): PropTypes.node` | -| onSectionRendered | Function | | Callback invoked with information about the section of the Grid that was just rendered. This callback is only invoked when visible rows have changed: `({ columnOverscanStartIndex: number, columnOverscanStopIndex: number, columnStartIndex: number, columnStopIndex: number, rowOverscanStartIndex: number, rowOverscanStopIndex: number, rowStartIndex: number, rowStopIndex: number }): void` | -| onScroll | Function | | Callback invoked whenever the scroll offset changes within the inner scrollable region: `({ clientHeight: number, clientWidth: number, scrollHeight: number, scrollLeft: number, scrollTop: number, scrollWidth: number }): void` | -| onScrollbarPresenceChange | Function | | Called whenever a horizontal or vertical scrollbar is added or removed: `({ horizontal: boolean, size: number, vertical: boolean }): void` | -| overscanColumnCount | Number | | Number of columns to render before/after the visible slice of the grid. This can help reduce flickering during scrolling on certain browsers/devices. See [here](overscanUsage.md) for an important note about this property. | -| overscanIndicesGetter | Function | | Responsible for calculating the number of cells to overscan before and after a specified range [Learn more](#overscanindicesgetter) | -| overscanRowCount | Number | | Number of rows to render above/below the visible slice of the grid. This can help reduce flickering during scrolling on certain browsers/devices. See [here](overscanUsage.md) for an important note about this property. | -| role | String | | Optional override of ARIA role default; defaults to `grid`. | -| rowCount | Number | ✓ | Number of rows in grid. | -| rowHeight | Number or Function | ✓ | Either a fixed row height (number) or a function that returns the height of a row given its index: `({ index: number }): number`. If function is used, specify `estimatedRowSize` for more consistent scrolling behavior. | -| scrollingResetTimeInterval | Number | | Wait this amount of time after the last scroll event before resetting Grid `pointer-events`; defaults to 150ms. | -| scrollLeft | Number | | Horizontal offset | -| scrollToAlignment | String | | Controls the alignment of scrolled-to-cells. The default ("_auto_") scrolls the least amount possible to ensure that the specified cell is fully visible. Use "_start_" to always align cells to the top/left of the `Grid` and "_end_" to align them bottom/right. Use "_center_" to align specified cell in the middle of container. | -| scrollToColumn | Number | | Column index to ensure visible (by forcefully scrolling if necessary). Takes precedence over `scrollLeft`. | -| scrollToRow | Number | | Row index to ensure visible (by forcefully scrolling if necessary). Takes precedence over `scrollTop`. | -| scrollTop | Number | | Vertical offset | -| style | Object | | Optional custom inline style to attach to root `Grid` element. | -| tabIndex | Number | | Optional override of tab index default; defaults to `0`. | -| width | Number | ✓ | Width of Grid; this property determines the number of visible (vs virtualized) columns. | + +| Property | Type | Required? | Description | +| :------------------------- | :----------------- | :-------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| autoContainerWidth | Boolean | | Set the width of the inner scrollable container to 'auto'. This is useful for single-column Grids to ensure that the column doesn't extend below a vertical scrollbar. | +| autoHeight | Boolean | | Outer `height` of `Grid` is set to "auto". This property should only be used in conjunction with the `WindowScroller` HOC. | +| autoWidth | Boolean | | Outer `width` of `Grid` is set to "auto". This property should only be used in conjunction with the `WindowScroller` HOC. | +| cellRangeRenderer | Function | | Responsible for rendering a group of cells given their index ranges. [Learn more](#cellrangerenderer) | +| cellRenderer | Function | ✓ | Responsible for rendering a cell given an row and column index. [Learn more](#cellrenderer) | +| className | String | | Optional custom CSS class name to attach to root `Grid` element. | +| columnCount | Number | ✓ | Number of columns in grid. | +| columnWidth | Number or Function | ✓ | Either a fixed column width (number) or a function that returns the width of a column given its index: `({ index: number }): number`. If function is used, specify `estimatedColumnSize` for more consistent scrolling behavior. | +| containerProps | Object | | Responsible for adding props to the cell-container, i.e. `onWheel`. | +| containerRole | string | | ARIA role for the cell-container; defaults to "rowgroup" | +| containerStyle | Object | | Optional custom inline style to attach to inner cell-container element. | +| deferredMeasurementCache | `CellMeasurer` | | If CellMeasurer is used to measure this Grid's children, this should be a pointer to its CellMeasurerCache. A shared CellMeasurerCache reference enables Grid and CellMeasurer to share measurement data. | +| estimatedColumnSize | Number | | Used to estimate the total width of a `Grid` before all of its columns have actually been measured. The estimated total width is adjusted as columns are rendered. | +| estimatedRowSize | Number | | Used to estimate the total height of a `Grid` before all of its rows have actually been measured. The estimated total height is adjusted as rows are rendered. | +| height | Number | ✓ | Height of Grid; this property determines the number of visible (vs virtualized) rows. | +| id | String | | Optional custom id to attach to root `Grid` element. | +| isScrolling | Boolean | | Override internal is-scrolling state tracking. This property is primarily intended for use with the WindowScroller component. | +| isScrollingOptOut | Boolean | | Prevents re-rendering of visible cells on scroll end. | +| noContentRenderer | Function | | Optional renderer to be rendered inside the grid when either `rowCount` or `columnCount` is empty: `(): PropTypes.node` | +| onSectionRendered | Function | | Callback invoked with information about the section of the Grid that was just rendered. This callback is only invoked when visible rows have changed: `({ columnOverscanStartIndex: number, columnOverscanStopIndex: number, columnStartIndex: number, columnStopIndex: number, rowOverscanStartIndex: number, rowOverscanStopIndex: number, rowStartIndex: number, rowStopIndex: number }): void` | +| onScroll | Function | | Callback invoked whenever the scroll offset changes within the inner scrollable region: `({ clientHeight: number, clientWidth: number, scrollHeight: number, scrollLeft: number, scrollTop: number, scrollWidth: number }): void` | +| onScrollbarPresenceChange | Function | | Called whenever a horizontal or vertical scrollbar is added or removed: `({ horizontal: boolean, size: number, vertical: boolean }): void` | +| overscanColumnCount | Number | | Number of columns to render before/after the visible slice of the grid. This can help reduce flickering during scrolling on certain browsers/devices. See [here](overscanUsage.md) for an important note about this property. | +| overscanIndicesGetter | Function | | Responsible for calculating the number of cells to overscan before and after a specified range [Learn more](#overscanindicesgetter) | +| overscanRowCount | Number | | Number of rows to render above/below the visible slice of the grid. This can help reduce flickering during scrolling on certain browsers/devices. See [here](overscanUsage.md) for an important note about this property. | +| role | String | | Optional override of ARIA role default; defaults to `grid`. | +| rowCount | Number | ✓ | Number of rows in grid. | +| rowHeight | Number or Function | ✓ | Either a fixed row height (number) or a function that returns the height of a row given its index: `({ index: number }): number`. If function is used, specify `estimatedRowSize` for more consistent scrolling behavior. | +| scrollingResetTimeInterval | Number | | Wait this amount of time after the last scroll event before resetting Grid `pointer-events`; defaults to 150ms. | +| scrollLeft | Number | | Horizontal offset | +| scrollToAlignment | String | | Controls the alignment of scrolled-to-cells. The default ("_auto_") scrolls the least amount possible to ensure that the specified cell is fully visible. Use "_start_" to always align cells to the top/left of the `Grid` and "_end_" to align them bottom/right. Use "_center_" to align specified cell in the middle of container. | +| scrollToColumn | Number | | Column index to ensure visible (by forcefully scrolling if necessary). Takes precedence over `scrollLeft`. | +| scrollToRow | Number | | Row index to ensure visible (by forcefully scrolling if necessary). Takes precedence over `scrollTop`. | +| scrollTop | Number | | Vertical offset | +| style | Object | | Optional custom inline style to attach to root `Grid` element. | +| tabIndex | Number | | Optional override of tab index default; defaults to `0`. | +| width | Number | ✓ | Width of Grid; this property determines the number of visible (vs virtualized) columns. | ### Public Methods @@ -93,10 +93,10 @@ Useful for animating position changes. The Grid component supports the following static class names -| Property | Description | -|:---|:---| -| ReactVirtualized__Grid | Main (outer) element | -| ReactVirtualized__Grid__innerScrollContainer | Inner scrollable area | +| Property | Description | +| :------------------------------------------- | :-------------------- | +| ReactVirtualized\_\_Grid | Main (outer) element | +| ReactVirtualized**Grid**innerScrollContainer | Inner scrollable area | ### cellRangeRenderer @@ -107,23 +107,16 @@ Many use cases can be solved more easily using the `onScroll` callback or the `S If you do want to override `cellRangeRenderer` the easiest way is to decorate the default implementation like so: ```jsx -import { defaultCellRangeRenderer, Grid } from 'react-virtualized' - -function cellRangeRenderer (props) { - const children = defaultCellRangeRenderer(props) - children.push( -
My custom overlay
- ) - return children +import {defaultCellRangeRenderer, Grid} from 'react-virtualized'; + +function cellRangeRenderer(props) { + const children = defaultCellRangeRenderer(props); + children.push(
My custom overlay
); + return children; } -function CustomizedGrid (props) { - return ( - - ) +function CustomizedGrid(props) { + return ; } ``` @@ -132,53 +125,60 @@ If you require greater customization, you may want to fork the [`defaultCellRang This function accepts the following named parameters: ```js -function cellRangeRenderer ({ - cellCache, // Temporary cell cache used while scrolling - cellRenderer, // Cell renderer prop supplied to Grid +function cellRangeRenderer({ + cellCache, // Temporary cell cache used while scrolling + cellRenderer, // Cell renderer prop supplied to Grid columnSizeAndPositionManager, // @see CellSizeAndPositionManager, - columnStartIndex, // Index of first column (inclusive) to render - columnStopIndex, // Index of last column (inclusive) to render - horizontalOffsetAdjustment, // Horizontal pixel offset (required for scaling) - isScrolling, // The Grid is currently being scrolled - rowSizeAndPositionManager, // @see CellSizeAndPositionManager, - rowStartIndex, // Index of first row (inclusive) to render - rowStopIndex, // Index of last row (inclusive) to render - scrollLeft, // Current horizontal scroll offset of Grid - scrollTop, // Current vertical scroll offset of Grid - styleCache, // Temporary style (size & position) cache used while scrolling - verticalOffsetAdjustment // Vertical pixel offset (required for scaling) + columnStartIndex, // Index of first column (inclusive) to render + columnStopIndex, // Index of last column (inclusive) to render + horizontalOffsetAdjustment, // Horizontal pixel offset (required for scaling) + isScrolling, // The Grid is currently being scrolled + rowSizeAndPositionManager, // @see CellSizeAndPositionManager, + rowStartIndex, // Index of first row (inclusive) to render + rowStopIndex, // Index of last row (inclusive) to render + scrollLeft, // Current horizontal scroll offset of Grid + scrollTop, // Current vertical scroll offset of Grid + styleCache, // Temporary style (size & position) cache used while scrolling + verticalOffsetAdjustment, // Vertical pixel offset (required for scaling) }) { - const renderedCells = [] + const renderedCells = []; for (let rowIndex = rowStartIndex; rowIndex <= rowStopIndex; rowIndex++) { // This contains :offset (top) and :size (height) information for the cell - let rowDatum = rowSizeAndPositionManager.getSizeAndPositionOfCell(rowIndex) + let rowDatum = rowSizeAndPositionManager.getSizeAndPositionOfCell(rowIndex); - for (let columnIndex = columnStartIndex; columnIndex <= columnStopIndex; columnIndex++) { + for ( + let columnIndex = columnStartIndex; + columnIndex <= columnStopIndex; + columnIndex++ + ) { // This contains :offset (left) and :size (width) information for the cell - let columnDatum = columnSizeAndPositionManager.getSizeAndPositionOfCell(columnIndex) + let columnDatum = columnSizeAndPositionManager.getSizeAndPositionOfCell( + columnIndex, + ); // Be sure to adjust cell position in case the total set of cells is too large to be supported by the browser natively. // In this case, Grid will shift cells as a user scrolls to increase cell density. - let left = columnDatum.offset + horizontalOffsetAdjustment - let top = rowDatum.offset + verticalOffsetAdjustment + let left = columnDatum.offset + horizontalOffsetAdjustment; + let top = rowDatum.offset + verticalOffsetAdjustment; // The rest of the information you need to render the cell are contained in the data. // Be sure to provide unique :key attributes. - let key = `${rowIndex}-${columnIndex}` - let height = rowDatum.size - let width = columnDatum.size + let key = `${rowIndex}-${columnIndex}`; + let height = rowDatum.size; + let width = columnDatum.size; // Now render your cell and additional UI as you see fit. // Add all rendered children to the :renderedCells Array. } } - return renderedCells + return renderedCells; } ``` ### overscanIndicesGetter + This is an advanced property. This function is responsible for calculating the number of cells to overscan before and after a specified range. By default, React Virtualized optimizes the number of cells to overscan based on scroll direction. If you'd like to customize this behavior, you may want to fork the [`defaultOverscanIndicesGetter`](https://github.com/bvaughn/react-virtualized/blob/master/source/Grid/defaultOverscanIndicesGetter.js) function. @@ -204,23 +204,21 @@ Responsible for rendering a single cell, given its row and column index. This function accepts the following named parameters: ```jsx -function cellRenderer ({ +function cellRenderer({ columnIndex, // Horizontal (column) index of cell isScrolling, // The Grid is currently being scrolled - isVisible, // This cell is visible within the grid (eg it is not an overscanned cell) - key, // Unique key within array of cells - parent, // Reference to the parent Grid (instance) - rowIndex, // Vertical (row) index of cell - style // Style object to be applied to cell (to position it); - // This must be passed through to the rendered cell element. + isVisible, // This cell is visible within the grid (eg it is not an overscanned cell) + key, // Unique key within array of cells + parent, // Reference to the parent Grid (instance) + rowIndex, // Vertical (row) index of cell + style, // Style object to be applied to cell (to position it); + // This must be passed through to the rendered cell element. }) { // Grid data is a 2d array in this example... - const user = list[rowIndex][columnIndex] + const user = list[rowIndex][columnIndex]; // If cell content is complex, consider rendering a lighter-weight placeholder while scrolling. - const content = isScrolling - ? '...' - : + const content = isScrolling ? '...' : ; // Style is required since it specifies how the cell is to be sized and positioned. // React Virtualized depends on this sizing/positioning for proper scrolling behavior. @@ -233,13 +231,10 @@ function cellRenderer ({ // 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 cells. return ( -
+
{content}
- ) + ); } ``` @@ -250,23 +245,20 @@ Below is a very basic `Grid` example. The grid displays an array of objects with ```jsx import React from 'react'; import ReactDOM from 'react-dom'; -import { Grid } from 'react-virtualized'; +import {Grid} from 'react-virtualized'; // Grid data as an array of arrays const list = [ - ['Brian Vaughn', 'Software Engineer', 'San Jose', 'CA', 95125 /* ... */ ] + ['Brian Vaughn', 'Software Engineer', 'San Jose', 'CA', 95125 /* ... */], // And so on... ]; -function cellRenderer ({ columnIndex, key, rowIndex, style }) { +function cellRenderer({columnIndex, key, rowIndex, style}) { return ( -
+
{list[rowIndex][columnIndex]}
- ) + ); } // Render your grid @@ -280,6 +272,6 @@ ReactDOM.render( rowHeight={30} width={300} />, - document.getElementById('example') + document.getElementById('example'), ); ``` diff --git a/docs/InfiniteLoader.md b/docs/InfiniteLoader.md index 28a0b46e0..f351f4a67 100644 --- a/docs/InfiniteLoader.md +++ b/docs/InfiniteLoader.md @@ -1,5 +1,4 @@ -InfiniteLoader ---------------- +## InfiniteLoader A component that manages just-in-time fetching of data as a user scrolls up or down in a list. @@ -11,30 +10,33 @@ This is an advanced component and can be confusing in certain situations. [See below for more information](#edge-cases-and-considerations). ### Prop Types -| Property | Type | Required? | Description | -|:---|:---|:---:|:---| -| children | Function | ✓ | Function responsible for rendering a virtualized component. This function should implement the following signature: `({ onRowsRendered: Function, registerChild: Function }) => PropTypes.element` | -| isRowLoaded | Function | ✓ | Function responsible for tracking the loaded state of each row. It should implement the following signature: `({ index: number }): boolean` | -| loadMoreRows | Function | ✓ | Callback to be invoked when more rows must be loaded. It should implement the following signature: `({ startIndex: number, stopIndex: number }): Promise`. The returned Promise should be resolved once row data has finished loading. It will be used to determine when to refresh the list with the newly-loaded data. This callback may be called multiple times in reaction to a single scroll event. | -| minimumBatchSize | Number | | Minimum number of rows to be loaded at a time. This property can be used to batch requests to reduce HTTP requests. Defaults to `10`. | -| rowCount | Number | ✓ | Number of rows in list; can be arbitrary high number if actual number is unknown. | -| threshold | Number | | Threshold at which to pre-fetch data. A threshold X means that data will start loading when a user scrolls within X rows. Defaults to `15`. | + +| Property | Type | Required? | Description | +| :--------------- | :------- | :-------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| children | Function | ✓ | Function responsible for rendering a virtualized component. This function should implement the following signature: `({ onRowsRendered: Function, registerChild: Function }) => PropTypes.element` | +| isRowLoaded | Function | ✓ | Function responsible for tracking the loaded state of each row. It should implement the following signature: `({ index: number }): boolean` | +| loadMoreRows | Function | ✓ | Callback to be invoked when more rows must be loaded. It should implement the following signature: `({ startIndex: number, stopIndex: number }): Promise`. The returned Promise should be resolved once row data has finished loading. It will be used to determine when to refresh the list with the newly-loaded data. This callback may be called multiple times in reaction to a single scroll event. | +| minimumBatchSize | Number | | Minimum number of rows to be loaded at a time. This property can be used to batch requests to reduce HTTP requests. Defaults to `10`. | +| rowCount | Number | ✓ | Number of rows in list; can be arbitrary high number if actual number is unknown. | +| threshold | Number | | Threshold at which to pre-fetch data. A threshold X means that data will start loading when a user scrolls within X rows. Defaults to `15`. | ### Public Methods ##### resetLoadMoreRowsCache (autoReload: boolean = false) + Reset any cached data about already-loaded rows. This method should be called if any/all loaded data needs to be refetched (eg a filtered list where the search criteria changes). If `autoReload` passed as true, the last loaded batch would be automatically reloaded. ### Children function The child function is passed the following named parameters: -| Parameter | Type | Description | -|:---|:---|:---| -| onRowsRendered | Function | This function should be passed as the child's `onRowsRendered` property. It informs the loader when the user is scrolling. | -| registerChild | Function | This function should be set as the child's `ref` property. It enables a set of rows to be refreshed once their data has finished loading. | +| Parameter | Type | Description | +| :------------- | :------- | :---------------------------------------------------------------------------------------------------------------------------------------- | +| onRowsRendered | Function | This function should be passed as the child's `onRowsRendered` property. It informs the loader when the user is scrolling. | +| registerChild | Function | This function should be set as the child's `ref` property. It enables a set of rows to be refreshed once their data has finished loading. | ### Examples + ###### InfiniteLoader and List This example uses `InfiniteLoader` to prefetch rows in a `List` list as a user scrolls. @@ -97,6 +99,7 @@ ReactDOM.render( ``` ###### InfiniteLoader and Grid + It is not common to use `InfiniteLoader` and `Grid` together but it is possible using an approach like this: ```jsx @@ -169,6 +172,7 @@ In that case it is possible that `InfiniteLoader` will not _know_ to call `loadM The easiest way to address this is for your application code to call `loadMoreRows` when it detects that the underlying collection may have changed. For example: + ```js _loadMoreRows ({ startIndex, stopIndex }) { this._loadMoreRowsStartIndex = startIndex diff --git a/docs/List.md b/docs/List.md index b2492cda5..ded07b303 100644 --- a/docs/List.md +++ b/docs/List.md @@ -1,35 +1,36 @@ -List ---------------- +## List This component renders a windowed list (rows) of elements. It uses a `Grid` internally to render the rows and all props are relayed to that inner `Grid`. That means that `List` also accepts [`Grid` props](Grid.md) in addition to the props shown below. ### Prop Types -| Property | Type | Required? | Description | -|:---|:---|:---:|:---| -| autoHeight | Boolean | | Outer `height` of `List` is set to "auto". This property should only be used in conjunction with the `WindowScroller` HOC. | -| className | String | | Optional custom CSS class name to attach to root `List` element. | -| estimatedRowSize | Number | | Used to estimate the total height of a `List` before all of its rows have actually been measured. The estimated total height is adjusted as rows are rendered. | -| height | Number | ✓ | Height constraint for list (determines how many actual rows are rendered) | -| id | String | | Optional custom id to attach to root `List` element. | -| noRowsRenderer | Function | | Callback used to render placeholder content when `rowCount` is 0 | -| onRowsRendered | Function | | Callback invoked with information about the slice of rows that were just rendered: `({ overscanStartIndex: number, overscanStopIndex: number, startIndex: number, stopIndex: number }): void` | -| onScroll | Function | | Callback invoked whenever the scroll offset changes within the inner scrollable region: `({ clientHeight: number, scrollHeight: number, scrollTop: number }): void` | -| overscanRowCount | Number | | Number of rows to render above/below the visible bounds of the list. This can help reduce flickering during scrolling on certain browsers/devices. See [here](overscanUsage.md) for an important note about this property. | -| rowCount | Number | ✓ | Number of rows in list. | -| rowHeight | Number or Function | ✓ | Either a fixed row height (number) or a function that returns the height of a row given its index: `({ index: number }): number` | -| rowRenderer | Function | ✓ | Responsible for rendering a row. [Learn more](#rowrenderer).| -| scrollToAlignment | String | | Controls the alignment scrolled-to-rows. The default ("_auto_") scrolls the least amount possible to ensure that the specified row is fully visible. Use "_start_" to always align rows to the top of the list and "_end_" to align them bottom. Use "_center_" to align them in the middle of container. | -| scrollToIndex | Number | | Row index to ensure visible (by forcefully scrolling if necessary) | -| scrollTop | Number | | Forced vertical scroll offset; can be used to synchronize scrolling between components | -| style | Object | | Optional custom inline style to attach to root `List` element. | -| tabIndex | Number | | Optional override of tab index default; defaults to `0`. | -| width | Number | ✓ | Width of the list | + +| Property | Type | Required? | Description | +| :---------------- | :----------------- | :-------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| autoHeight | Boolean | | Outer `height` of `List` is set to "auto". This property should only be used in conjunction with the `WindowScroller` HOC. | +| className | String | | Optional custom CSS class name to attach to root `List` element. | +| estimatedRowSize | Number | | Used to estimate the total height of a `List` before all of its rows have actually been measured. The estimated total height is adjusted as rows are rendered. | +| height | Number | ✓ | Height constraint for list (determines how many actual rows are rendered) | +| id | String | | Optional custom id to attach to root `List` element. | +| noRowsRenderer | Function | | Callback used to render placeholder content when `rowCount` is 0 | +| onRowsRendered | Function | | Callback invoked with information about the slice of rows that were just rendered: `({ overscanStartIndex: number, overscanStopIndex: number, startIndex: number, stopIndex: number }): void` | +| onScroll | Function | | Callback invoked whenever the scroll offset changes within the inner scrollable region: `({ clientHeight: number, scrollHeight: number, scrollTop: number }): void` | +| overscanRowCount | Number | | Number of rows to render above/below the visible bounds of the list. This can help reduce flickering during scrolling on certain browsers/devices. See [here](overscanUsage.md) for an important note about this property. | +| rowCount | Number | ✓ | Number of rows in list. | +| rowHeight | Number or Function | ✓ | Either a fixed row height (number) or a function that returns the height of a row given its index: `({ index: number }): number` | +| rowRenderer | Function | ✓ | Responsible for rendering a row. [Learn more](#rowrenderer). | +| scrollToAlignment | String | | Controls the alignment scrolled-to-rows. The default ("_auto_") scrolls the least amount possible to ensure that the specified row is fully visible. Use "_start_" to always align rows to the top of the list and "_end_" to align them bottom. Use "_center_" to align them in the middle of container. | +| scrollToIndex | Number | | Row index to ensure visible (by forcefully scrolling if necessary) | +| scrollTop | Number | | Forced vertical scroll offset; can be used to synchronize scrolling between components | +| style | Object | | Optional custom inline style to attach to root `List` element. | +| tabIndex | Number | | Optional override of tab index default; defaults to `0`. | +| width | Number | ✓ | Width of the list | ### Public Methods ##### forceUpdateGrid + Forcefully re-render the inner `Grid` component. Calling `forceUpdate` on `List` may not re-render the inner `Grid` since it uses `shallowCompare` as a performance optimization. @@ -41,12 +42,14 @@ This may be appropriate if the underlying row data has changed but the row sizes Gets offset for a given row and alignment. ##### measureAllRows + Pre-measure all rows in a `List`. Typically rows are only measured as needed and estimated heights are used for cells that have not yet been measured. This method ensures that the next call to getTotalSize() returns an exact size (as opposed to just an estimated one). ##### recomputeRowHeights (index: number) + Recompute row heights and offsets after the specified index (defaults to 0). `List` has no way of knowing when its underlying list data has changed since it only receives a `rowHeight` property. @@ -71,21 +74,19 @@ Responsible for rendering a single row, given its index. This function accepts the following named parameters: ```jsx -function rowRenderer ({ - index, // Index of row +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. + 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] + const user = list[index]; // If row content is complex, consider rendering a light-weight placeholder while scrolling. - const content = isScrolling - ? '...' - : + 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. @@ -98,13 +99,10 @@ function rowRenderer ({ // 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}
- ) + ); } ``` @@ -112,9 +110,9 @@ function rowRenderer ({ The List component supports the following static class names -| Property | Description | -|:---|:---| -| ReactVirtualized__List | Main (outer) element | +| Property | Description | +| :----------------------- | :------------------- | +| ReactVirtualized\_\_List | Main (outer) element | ### Examples @@ -127,29 +125,26 @@ For this reason it is recommended that your rows use a style like `overflow-y: h ```javascript import React from 'react'; import ReactDOM from 'react-dom'; -import { List } from 'react-virtualized'; +import {List} from 'react-virtualized'; // List data as an array of strings const list = [ - 'Brian Vaughn' + 'Brian Vaughn', // And so on... ]; -function rowRenderer ({ - key, // Unique key within array of rows - index, // Index of row within collection +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) + 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 @@ -161,6 +156,6 @@ ReactDOM.render( rowHeight={20} rowRenderer={rowRenderer} />, - document.getElementById('example') + document.getElementById('example'), ); ``` diff --git a/docs/Masonry.md b/docs/Masonry.md index 47594e809..1681cb5a0 100644 --- a/docs/Masonry.md +++ b/docs/Masonry.md @@ -1,47 +1,55 @@ The `Masonry` component efficiently displays dynamically-sized, user-positioned cells using windowing techniques. Cell positions are controlled by an injected `cellPositioner` property. Windowing is vertical; this component does not support horizontal scrolling. ### Overview + #### Measuring and layout + Rendering occurs in two phases: ##### Phase 1: Measurement + This phase uses estimated cell sizes (provided by the `cellMeasurerCache` property) to determine how many cells to measure in a batch. Batch size is chosen using a fast, naive layout algorithm that stacks images in order until the viewport has been filled. After measurement is complete (`componentDidMount` or `componentDidUpdate`) this component evaluates positioned cells in order to determine if another measurement pass is required (eg if actual cell sizes were less than estimated sizes). All measurements are permanently cached (keyed by `keyMapper`) for performance purposes. + ##### Phase 2: Layout + This phase uses the external `cellPositioner` to position cells. At this time the positioner has access to cached size measurements for all cells. The positions it returns are cached by `Masonry` for fast access later. Phase one is repeated if the user scrolls beyond the current layout's bounds. If the layout is invalidated due to eg a resize, cached positions can be cleared using `recomputeCellPositions()` or `clearCellPositions()`. #### Animation Constraints -* Simple animations are supported (eg translate/slide into place on initial reveal). -* More complex animations are not (eg flying from one position to another on resize). + +- Simple animations are supported (eg translate/slide into place on initial reveal). +- More complex animations are not (eg flying from one position to another on resize). #### Layout Constraints -* This component supports a multi-column layout. -* Each item can have a unique, lazily-measured height. -* The width of all items in a column must be equal. (Items may not span multiple columns.) -* The left position of all items within a column must align. -* Cell measurements must be synchronous. Size impacts layout and async measurements would require frequent layout invalidation. Support for this may be added in the future but for now the use of the `CellMeasurer` render callback's async `measure` parameter is not supported. + +- This component supports a multi-column layout. +- Each item can have a unique, lazily-measured height. +- The width of all items in a column must be equal. (Items may not span multiple columns.) +- The left position of all items within a column must align. +- Cell measurements must be synchronous. Size impacts layout and async measurements would require frequent layout invalidation. Support for this may be added in the future but for now the use of the `CellMeasurer` render callback's async `measure` parameter is not supported. ### Prop Types -| Property | Type | Required? | Description | -|:---|:---|:---:|:---| -| cellCount | number | ✓ | Total number of items | -| cellMeasurerCache | mixed | ✓ | Caches item measurements. Default sizes help `Masonry` decide how many images to batch-measure. Learn more [here](CellMeasurer.md#cellmeasurercache). | -| cellPositioner | function | ✓ | Positions a cell given an index: `(index: number) => ({ left: number, top: number })`. [Learn more](#createmasonrycellpositioner) | -| cellRenderer | function | ✓ | Responsible for rendering a cell given an index. [Learn more](#cellrenderer) | -| className | string | | Optional custom CSS class name to attach to root `Masonry` element. | -| height | number | ✓ | Height of the component; this value determines the number of visible items. | -| id | string | | Optional custom id to attach to root `Masonry` element. | -| keyMapper | function | | Maps an index to a unique id to store cached measurement and position info for a cell. This prevents eg cached measurements from being invalidated when a collection is re-ordered. `(index: number) => any` | -| onCellsRendered | function | | Callback invoked with information about the cells that were most recently rendered. This callback is only invoked when visible cells have changed: `({ startIndex: number, stopIndex: number }): void` | -| onScroll | function | | Callback invoked whenever the scroll offset changes within the inner scrollable region: `({ clientHeight: number, scrollHeight: number, scrollTop: number }): void` | -| overscanByPixels | number | | Render this many additional pixels above and below the viewport. This helps reduce flicker when a user scrolls quickly. Defaults to 20. | -| role | string | | Optional override of ARIA role default; defaults to "grid". | -| scrollingResetTimeInterval | number | | Wait this amount of time after the last scroll event before resetting `pointer-events`; defaults to 150ms. | -| style | mixed | | Optional custom inline style to attach to root `Masonry` element. | -| tabIndex | number | | Optional override of tab index default; defaults to 0. | -| width | number | ✓ | Width of the component; this value determines the number of visible items. | -| rowDirection | string | | row direction of items, can be ```ltr``` or ```rtl``` defaults to ```ltr``` | + +| Property | Type | Required? | Description | +| :------------------------- | :------- | :-------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| cellCount | number | ✓ | Total number of items | +| cellMeasurerCache | mixed | ✓ | Caches item measurements. Default sizes help `Masonry` decide how many images to batch-measure. Learn more [here](CellMeasurer.md#cellmeasurercache). | +| cellPositioner | function | ✓ | Positions a cell given an index: `(index: number) => ({ left: number, top: number })`. [Learn more](#createmasonrycellpositioner) | +| cellRenderer | function | ✓ | Responsible for rendering a cell given an index. [Learn more](#cellrenderer) | +| className | string | | Optional custom CSS class name to attach to root `Masonry` element. | +| height | number | ✓ | Height of the component; this value determines the number of visible items. | +| id | string | | Optional custom id to attach to root `Masonry` element. | +| keyMapper | function | | Maps an index to a unique id to store cached measurement and position info for a cell. This prevents eg cached measurements from being invalidated when a collection is re-ordered. `(index: number) => any` | +| onCellsRendered | function | | Callback invoked with information about the cells that were most recently rendered. This callback is only invoked when visible cells have changed: `({ startIndex: number, stopIndex: number }): void` | +| onScroll | function | | Callback invoked whenever the scroll offset changes within the inner scrollable region: `({ clientHeight: number, scrollHeight: number, scrollTop: number }): void` | +| overscanByPixels | number | | Render this many additional pixels above and below the viewport. This helps reduce flicker when a user scrolls quickly. Defaults to 20. | +| role | string | | Optional override of ARIA role default; defaults to "grid". | +| scrollingResetTimeInterval | number | | Wait this amount of time after the last scroll event before resetting `pointer-events`; defaults to 150ms. | +| style | mixed | | Optional custom inline style to attach to root `Masonry` element. | +| tabIndex | number | | Optional override of tab index default; defaults to 0. | +| width | number | ✓ | Width of the component; this value determines the number of visible items. | +| rowDirection | string | | row direction of items, can be `ltr` or `rtl` defaults to `ltr` | ## Public Methods @@ -58,24 +66,21 @@ Resets internal position cache, synchronously re-computes positions, then force- Responsible for rendering a single cell given its index. This function accepts the following named parameters: ```jsx -function cellRenderer ({ - index, // Index of item within the collection +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. + 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 */} -
+ parent={parent}> +
{/* Your content goes here */}
); } @@ -85,12 +90,12 @@ function cellRenderer ({ `Masonry` provides a built-in positioner for a simple layout. This positioner requires a few configuration settings: -| Property | Type | Required? | Description | -|:---|:---|:---:|:---| -| cellMeasurerCache | `CellMeasurerCache` | ✓ | Contains cell measurements (eg item height). | -| columnCount | number | ✓ | Number of columns to use in layout. | -| columnWidth | number | ✓ | Column width. | -| spacer | number | | Empty space between columns; defaults to 0. | +| Property | Type | Required? | Description | +| :---------------- | :------------------ | :-------: | :------------------------------------------- | +| cellMeasurerCache | `CellMeasurerCache` | ✓ | Contains cell measurements (eg item height). | +| columnCount | number | ✓ | Number of columns to use in layout. | +| columnWidth | number | ✓ | Column width. | +| spacer | number | | Empty space between columns; defaults to 0. | You can use this layout as shown below: @@ -99,20 +104,20 @@ const cellPositioner = createMasonryCellPositioner({ cellMeasurerCache: cache, columnCount: 3, columnWidth: 200, - spacer: 10 -}) + spacer: 10, +}); -let masonryRef +let masonryRef; -function renderMasonry (props) { +function renderMasonry(props) { return ( masonryRef = ref} + ref={ref => (masonryRef = ref)} {...props} /> - ) + ); } ``` @@ -122,10 +127,10 @@ If any of the configuration settings change due to external changes (eg window r cellPositioner.reset({ columnCount: 4, columnWidth: 250, - spacer: 15 -}) + spacer: 15, +}); -masonryRef.recomputeCellPositions() +masonryRef.recomputeCellPositions(); ``` ### Basic `Masonry` Example @@ -139,7 +144,7 @@ import { CellMeasurer, CellMeasurerCache, createMasonryCellPositioner, - Masonry + Masonry, } from 'react-virtualized'; // Array of images with captions @@ -149,39 +154,34 @@ const list = []; const cache = new CellMeasurerCache({ defaultHeight: 250, defaultWidth: 200, - fixedWidth: true -}) + 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 -}) + spacer: 10, +}); -function cellRenderer ({ index, key, parent, style }) { - const datum = list[index] +function cellRenderer({index, key, parent, style}) { + const datum = list[index]; return ( - +

{datum.caption}

- ) + ); } // Render your grid @@ -194,7 +194,7 @@ ReactDOM.render( height={600} width={800} />, - document.getElementById('example') + document.getElementById('example'), ); ``` @@ -210,15 +210,15 @@ These specifics were taken into account in a small library here is an example with dynamically measured images: ```js -import React from "react"; -import { render } from "react-dom"; +import React from 'react'; +import {render} from 'react-dom'; import { CellMeasurer, CellMeasurerCache, createMasonryCellPositioner, - Masonry -} from "react-virtualized"; -import ImageMeasurer from "react-virtualized-image-measurer"; + Masonry, +} from 'react-virtualized'; +import ImageMeasurer from 'react-virtualized-image-measurer'; // Array of images with captions //const list = [{image: 'http://...', title: 'Foo'}]; @@ -226,7 +226,7 @@ import ImageMeasurer from "react-virtualized-image-measurer"; // 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() + image: item.image + '?noCache=' + Math.random(), })); const columnWidth = 200; @@ -237,7 +237,7 @@ const defaultWidth = columnWidth; const cache = new CellMeasurerCache({ defaultHeight, defaultWidth, - fixedWidth: true + fixedWidth: true, }); // Our masonry layout will use 3 columns with a 10px gutter between @@ -245,13 +245,12 @@ const cellPositioner = createMasonryCellPositioner({ cellMeasurerCache: cache, columnCount: 3, columnWidth, - spacer: 10 + spacer: 10, }); -const MasonryComponent = ({ itemsWithSizes }) => { - - function cellRenderer({ index, key, parent, style }) { - const { item, size } = itemsWithSizes[index]; +const MasonryComponent = ({itemsWithSizes}) => { + function cellRenderer({index, key, parent, style}) { + const {item, size} = itemsWithSizes[index]; const height = columnWidth * (size.height / size.width) || defaultHeight; return ( @@ -262,7 +261,7 @@ const MasonryComponent = ({ itemsWithSizes }) => { alt={item.title} style={{ height: height, - width: columnWidth + width: columnWidth, }} />

{item.title}

@@ -289,14 +288,11 @@ render( items={noCacheList} image={item => item.image} defaultHeight={defaultHeight} - defaultWidth={defaultWidth} - > - {({ itemsWithSizes }) => ( - - )} + defaultWidth={defaultWidth}> + {({itemsWithSizes}) => } , - document.getElementById("root") + document.getElementById('root'), ); ``` -Live demo: https://codesandbox.io/s/7y66p25qv6 \ No newline at end of file +Live demo: https://codesandbox.io/s/7y66p25qv6 diff --git a/docs/MultiGrid.md b/docs/MultiGrid.md index 2b60bd9d6..77b4bfb9b 100644 --- a/docs/MultiGrid.md +++ b/docs/MultiGrid.md @@ -1,5 +1,4 @@ -MultiGrid ---------------- +## MultiGrid Decorates `Grid` and adds fixed columns and/or rows. This is already possible using `ScrollSync` and 2 or more `Grid`s but `MultiGrid` reduces the boilerplate. @@ -8,24 +7,25 @@ The majority of `MultiGrid` properties (eg `cellRenderer`) are relayed to all ch Some properties (eg `columnCount`, `rowCount`) are adjusted slightly to supported fixed rows and columns. ### Prop Types -| Property | Type | Required? | Description | -|:---|:---|:---:|:---| -| classNameBottomLeftGrid | string | | Optional custom className to attach to bottom-left `Grid` element. | -| classNameBottomRightGrid | string | | Optional custom className to attach to bottom-right `Grid` element. | -| classNameTopLeftGrid | string | | Optional custom className to attach to top-left `Grid` element. | -| classNameTopRightGrid | string | | Optional custom className to attach to top-right `Grid` element. | -| enableFixedColumnScroll | boolean | | Fixed column can be actively scrolled; disabled by default | -| enableFixedRowScroll | boolean | | Fixed row can be actively scrolled; disabled by default | -| fixedColumnCount | number | | Number of fixed columns; defaults to `0` | -| fixedRowCount | number | | Number of fixed rows; defaults to `0` | -| onScrollbarPresenceChange | Function | | Called whenever a horizontal or vertical scrollbar is added or removed from the bottom, right `Grid`.: `({ horizontal: boolean, size: number, vertical: boolean }): void` | -| style | object | | Optional custom inline style to attach to root `MultiGrid` element. | -| styleBottomLeftGrid | object | | Optional custom inline style to attach to bottom-left `Grid` element. | -| styleBottomRightGrid | object | | Optional custom inline style to attach to bottom-right `Grid` element. | -| styleTopLeftGrid | object | | Optional custom inline style to attach to top-left `Grid` element. | -| styleTopRightGrid | object | | Optional custom inline style to attach to top-right `Grid` element. | -| hideTopRightGridScrollbar | boolean | | Optional hides top-right `Grid` scrollbar by adding an additional wrapper. Only useful if `enableFixedRowScroll` is set to `true` | -| hideBottomLeftGridScrollbar | boolean | | Optional hides bottom-left `Grid` scrollbar by adding an additional wrapper. Only useful if `enableFixedColumnScroll` is set to `true` | + +| Property | Type | Required? | Description | +| :-------------------------- | :------- | :-------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| classNameBottomLeftGrid | string | | Optional custom className to attach to bottom-left `Grid` element. | +| classNameBottomRightGrid | string | | Optional custom className to attach to bottom-right `Grid` element. | +| classNameTopLeftGrid | string | | Optional custom className to attach to top-left `Grid` element. | +| classNameTopRightGrid | string | | Optional custom className to attach to top-right `Grid` element. | +| enableFixedColumnScroll | boolean | | Fixed column can be actively scrolled; disabled by default | +| enableFixedRowScroll | boolean | | Fixed row can be actively scrolled; disabled by default | +| fixedColumnCount | number | | Number of fixed columns; defaults to `0` | +| fixedRowCount | number | | Number of fixed rows; defaults to `0` | +| onScrollbarPresenceChange | Function | | Called whenever a horizontal or vertical scrollbar is added or removed from the bottom, right `Grid`.: `({ horizontal: boolean, size: number, vertical: boolean }): void` | +| style | object | | Optional custom inline style to attach to root `MultiGrid` element. | +| styleBottomLeftGrid | object | | Optional custom inline style to attach to bottom-left `Grid` element. | +| styleBottomRightGrid | object | | Optional custom inline style to attach to bottom-right `Grid` element. | +| styleTopLeftGrid | object | | Optional custom inline style to attach to top-left `Grid` element. | +| styleTopRightGrid | object | | Optional custom inline style to attach to top-right `Grid` element. | +| hideTopRightGridScrollbar | boolean | | Optional hides top-right `Grid` scrollbar by adding an additional wrapper. Only useful if `enableFixedRowScroll` is set to `true` | +| hideBottomLeftGridScrollbar | boolean | | Optional hides bottom-left `Grid` scrollbar by adding an additional wrapper. Only useful if `enableFixedColumnScroll` is set to `true` | ### Public Methods @@ -44,9 +44,9 @@ Pass-thru that calls `recomputeGridSize` on all child `Grid`s. ### Examples ```jsx -import { MultiGrid } from 'react-virtualized' +import {MultiGrid} from 'react-virtualized'; -function render () { +function render() { return ( - ) + ); } ``` diff --git a/docs/README.md b/docs/README.md index 356b3a21d..fffbebc4b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,32 +1,31 @@ -Documentation ---------------- +## Documentation ### Components -* [Collection](Collection.md) -* [Grid](Grid.md) -* [List](List.md) -* [Masonry](Masonry.md) -* [Table](Table.md) - * [Column](Column.md) - * [SortDirection](SortDirection.md) +- [Collection](Collection.md) +- [Grid](Grid.md) +- [List](List.md) +- [Masonry](Masonry.md) +- [Table](Table.md) + - [Column](Column.md) + - [SortDirection](SortDirection.md) ### High-Order Components -* [ArrowKeyStepper](ArrowKeyStepper.md) -* [AutoSizer](AutoSizer.md) -* [CellMeasurer](CellMeasurer.md) -* [ColumnSizer](ColumnSizer.md) -* [InfiniteLoader](InfiniteLoader.md) -* [MultiGrid](MultiGrid.md) -* [ScrollSync](ScrollSync.md) -* [WindowScroller](WindowScroller.md) +- [ArrowKeyStepper](ArrowKeyStepper.md) +- [AutoSizer](AutoSizer.md) +- [CellMeasurer](CellMeasurer.md) +- [ColumnSizer](ColumnSizer.md) +- [InfiniteLoader](InfiniteLoader.md) +- [MultiGrid](MultiGrid.md) +- [ScrollSync](ScrollSync.md) +- [WindowScroller](WindowScroller.md) ### How-to Guides -* [Customizing classes and styles](customizingStyles.md) -* [Displaying items in reverse order](reverseList.md) -* [Using AutoSizer](usingAutoSizer.md) -* [Creating an infinite-loading list](creatingAnInfiniteLoadingList.md) -* [Natural sort Table](tableWithNaturalSort.md) -* [Sorting a Table by multiple columns](multiColumnSortTable.md) \ No newline at end of file +- [Customizing classes and styles](customizingStyles.md) +- [Displaying items in reverse order](reverseList.md) +- [Using AutoSizer](usingAutoSizer.md) +- [Creating an infinite-loading list](creatingAnInfiniteLoadingList.md) +- [Natural sort Table](tableWithNaturalSort.md) +- [Sorting a Table by multiple columns](multiColumnSortTable.md) diff --git a/docs/ScrollSync.md b/docs/ScrollSync.md index d89a61891..6d515969d 100644 --- a/docs/ScrollSync.md +++ b/docs/ScrollSync.md @@ -1,55 +1,57 @@ -ScrollSync ---------------- +## ScrollSync High order component that simplifies the process of synchronizing scrolling between two or more virtualized components. ### Prop Types -| Property | Type | Required? | Description | -|:---|:---|:---:|:---| -| children | Function | ✓ | Function responsible for rendering 2 or more virtualized components. [See below](#children-function) for details about this function's signature. | + +| Property | Type | Required? | Description | +| :------- | :------- | :-------: | :------------------------------------------------------------------------------------------------------------------------------------------------ | +| children | Function | ✓ | Function responsible for rendering 2 or more virtualized components. [See below](#children-function) for details about this function's signature. | ### Children function The child function is passed the following named parameters: -| Parameter | Type | Description | -|:---|:---|:---| -| clientHeight | Number | Height of the visible portion of the `Grid` (or other scroll-synced component) | -| clientWidth | Number | Width of the visible portion of the `Grid` (or other scroll-synced component) | -| onScroll | Function | This function should be passed through to at least one of the virtualized child components. Updates to it will trigger updates to the scroll offset parameters which will in turn update the other virtualized children. | -| scrollHeight | Number | Total height of all rows in the `Grid` (or other scroll-synced component) | -| scrollLeft | Number | The current scroll-left offset. | -| scrollTop | Number | The current scroll-top offset. | -| scrollWidth | Number | Total width of all rows in the `Grid` (or other scroll-synced component) | +| Parameter | Type | Description | +| :----------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| clientHeight | Number | Height of the visible portion of the `Grid` (or other scroll-synced component) | +| clientWidth | Number | Width of the visible portion of the `Grid` (or other scroll-synced component) | +| onScroll | Function | This function should be passed through to at least one of the virtualized child components. Updates to it will trigger updates to the scroll offset parameters which will in turn update the other virtualized children. | +| scrollHeight | Number | Total height of all rows in the `Grid` (or other scroll-synced component) | +| scrollLeft | Number | The current scroll-left offset. | +| scrollTop | Number | The current scroll-top offset. | +| scrollWidth | Number | Total width of all rows in the `Grid` (or other scroll-synced component) | ### Examples This example uses `ScrollSync` to create a fixed row of columns to go along with a scrollable grid. ```jsx -import { Grid, List, ScrollSync } from 'react-virtualized' +import {Grid, List, ScrollSync} from 'react-virtualized'; import 'react-virtualized/styles.css'; // only needs to be imported once -function render (props) { +function render(props) { return ( - {({ clientHeight, clientWidth, onScroll, scrollHeight, scrollLeft, scrollTop, scrollWidth }) => ( -
-
- + {({ + clientHeight, + clientWidth, + onScroll, + scrollHeight, + scrollLeft, + scrollTop, + scrollWidth, + }) => ( +
+
+
-
- +
+
)} - ) + ); } ``` diff --git a/docs/SortDirection.md b/docs/SortDirection.md index 992ce32cc..2a4f3dece 100644 --- a/docs/SortDirection.md +++ b/docs/SortDirection.md @@ -1,12 +1,13 @@ -SortDirection ---------------- +## SortDirection Specifies which direction [Table](Table.md) data is currently sorted in. #### SortDirection.ASC + Sort items in ascending order. This means arranging from the lowest value to the highest (e.g. a-z, 0-9). #### SortDirection.DESC + Sort items in descending order. This means arranging from the highest value to the lowest (e.g. z-a, 9-0). diff --git a/docs/Table.md b/docs/Table.md index 3309b24d9..0c918f906 100644 --- a/docs/Table.md +++ b/docs/Table.md @@ -1,56 +1,57 @@ -Table ---------------- +## Table Table component with fixed headers and windowed rows for improved performance with large data sets. This component expects explicit `width` and `height` parameters. `Table` content can scroll vertically but it is not meant to scroll horizontally. ### Prop Types -| Property | Type | Required? | Description | -|:---|:---|:---:|:---| -| autoHeight | Boolean | | Outer `height` of `Table` is set to "auto". This property should only be used in conjunction with the `WindowScroller` HOC. | -| children | [Column](Column.md) | ✓ | One or more Columns describing the data displayed in this table | -| className | String | | Optional custom CSS class name to attach to root `Table` element. | -| disableHeader | Boolean | | Do not render the table header (only the rows) | -| estimatedRowSize | Number | | Used to estimate the total height of a `Table` before all of its rows have actually been measured. The estimated total height is adjusted as rows are rendered. | -| gridClassName | String | | Optional custom CSS class name to attach to inner Grid element | -| gridStyle | Object | | Optional inline style to attach to inner Grid element | -| headerClassName | String | | CSS class to apply to all column headers | -| headerHeight | Number | ✓ | Fixed height of header row | -| headerRowRenderer | Function | | Responsible for rendering the table header row given an array of columns. [Learn more](#headerrowrenderer) | -| headerStyle | Object | | Optional custom inline style to attach to table header columns. | -| height | Number | ✓ | Fixed/available height for out DOM element | -| id | String | | Optional custom id to attach to root `Table` element. | -| noRowsRenderer | Function | | Callback used to render placeholder content when :rowCount is 0 | -| onColumnClick | Function | | Callback invoked when a user clicks on a table column. `({ columnData: any, dataKey: string, event: Event }): void` | -| onHeaderClick | Function | | Callback invoked when a user clicks on a table header. `({ columnData: any, dataKey: string, event: Event }): void` | -| onRowClick | Function | | Callback invoked when a user clicks on a table row. `({ event: Event, index: number, rowData: any }): void` | -| onRowDoubleClick | Function | | Callback invoked when a user double-clicks on a table row. `({ event: Event, index: number, rowData: any }): void` | -| onRowMouseOut | Function | | Callback invoked when the mouse leaves a table row. `({ event: Event, index: number, rowData: any }): void` | -| onRowMouseOver | Function | | Callback invoked when a user moves the mouse over a table row. `({ event: Event, index: number, rowData: any }): void` | -| onRowRightClick | Function | | Callback invoked when a user right-clicks on a table row. `({ event: Event, index: number, rowData: any }): void` | -| onRowsRendered | Function | | Callback invoked with information about the slice of rows that were just rendered: `({ overscanStartIndex: number, overscanStopIndex: number, startIndex: number, stopIndex: number }): void` | -| overscanRowCount | Number | | Number of rows to render above/below the visible bounds of the list. This can help reduce flickering during scrolling on certain browsers/devices. See [here](overscanUsage.md) for an important note about this property. | -| onScroll | Function | | Callback invoked whenever the scroll offset changes within the inner scrollable region: `({ clientHeight: number, scrollHeight: number, scrollTop: number }): void` | -| rowClassName | String or Function | | CSS class to apply to all table rows (including the header row). This value may be either a static string or a function with the signature `({ index: number }): string`. Note that for the header row an index of `-1` is provided. | -| rowCount | Number | ✓ | Number of rows in table. | -| rowGetter | Function | ✓ | Callback responsible for returning a data row given an index. `({ index: int }): any` | -| rowHeight | Number or Function | ✓ | Either a fixed row height (number) or a function that returns the height of a row given its index: `({ index: number }): number` | -| rowRenderer | Function | | Responsible for rendering a table row given an array of columns. [Learn more](#rowrenderer) | -| rowStyle | Object or Function | | Optional custom inline style to attach to table rows. This value may be either a style object or a function with the signature `({ index: number }): Object`. Note that for the header row an index of `-1` is provided. | -| scrollToAlignment | String | | Controls the alignment scrolled-to-rows. The default ("_auto_") scrolls the least amount possible to ensure that the specified row is fully visible. Use "_start_" to always align rows to the top of the list and "_end_" to align them bottom. Use "_center_" to align them in the middle of container. | -| scrollToIndex | Number | | Row index to ensure visible (by forcefully scrolling if necessary) | -| scrollTop | Number | | Vertical offset | -| sort | Function | | Sort function to be called if a sortable header is clicked. `({ defaultSortDirection: string, event: MouseEvent, sortBy: string, sortDirection: SortDirection }): void` | -| sortBy | String | | Data is currently sorted by this `dataKey` (if it is sorted at all) | -| sortDirection | [SortDirection](SortDirection.md) | | Data is currently sorted in this direction (if it is sorted at all) | -| style | Object | | Optional custom inline style to attach to root `Table` element. | -| tabIndex | Number | | Optional override of inner `Grid` tab index default; defaults to `0`. | -| width | Number | ✓ | Width of the table | + +| Property | Type | Required? | Description | +| :---------------- | :-------------------------------- | :-------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| autoHeight | Boolean | | Outer `height` of `Table` is set to "auto". This property should only be used in conjunction with the `WindowScroller` HOC. | +| children | [Column](Column.md) | ✓ | One or more Columns describing the data displayed in this table | +| className | String | | Optional custom CSS class name to attach to root `Table` element. | +| disableHeader | Boolean | | Do not render the table header (only the rows) | +| estimatedRowSize | Number | | Used to estimate the total height of a `Table` before all of its rows have actually been measured. The estimated total height is adjusted as rows are rendered. | +| gridClassName | String | | Optional custom CSS class name to attach to inner Grid element | +| gridStyle | Object | | Optional inline style to attach to inner Grid element | +| headerClassName | String | | CSS class to apply to all column headers | +| headerHeight | Number | ✓ | Fixed height of header row | +| headerRowRenderer | Function | | Responsible for rendering the table header row given an array of columns. [Learn more](#headerrowrenderer) | +| headerStyle | Object | | Optional custom inline style to attach to table header columns. | +| height | Number | ✓ | Fixed/available height for out DOM element | +| id | String | | Optional custom id to attach to root `Table` element. | +| noRowsRenderer | Function | | Callback used to render placeholder content when :rowCount is 0 | +| onColumnClick | Function | | Callback invoked when a user clicks on a table column. `({ columnData: any, dataKey: string, event: Event }): void` | +| onHeaderClick | Function | | Callback invoked when a user clicks on a table header. `({ columnData: any, dataKey: string, event: Event }): void` | +| onRowClick | Function | | Callback invoked when a user clicks on a table row. `({ event: Event, index: number, rowData: any }): void` | +| onRowDoubleClick | Function | | Callback invoked when a user double-clicks on a table row. `({ event: Event, index: number, rowData: any }): void` | +| onRowMouseOut | Function | | Callback invoked when the mouse leaves a table row. `({ event: Event, index: number, rowData: any }): void` | +| onRowMouseOver | Function | | Callback invoked when a user moves the mouse over a table row. `({ event: Event, index: number, rowData: any }): void` | +| onRowRightClick | Function | | Callback invoked when a user right-clicks on a table row. `({ event: Event, index: number, rowData: any }): void` | +| onRowsRendered | Function | | Callback invoked with information about the slice of rows that were just rendered: `({ overscanStartIndex: number, overscanStopIndex: number, startIndex: number, stopIndex: number }): void` | +| overscanRowCount | Number | | Number of rows to render above/below the visible bounds of the list. This can help reduce flickering during scrolling on certain browsers/devices. See [here](overscanUsage.md) for an important note about this property. | +| onScroll | Function | | Callback invoked whenever the scroll offset changes within the inner scrollable region: `({ clientHeight: number, scrollHeight: number, scrollTop: number }): void` | +| rowClassName | String or Function | | CSS class to apply to all table rows (including the header row). This value may be either a static string or a function with the signature `({ index: number }): string`. Note that for the header row an index of `-1` is provided. | +| rowCount | Number | ✓ | Number of rows in table. | +| rowGetter | Function | ✓ | Callback responsible for returning a data row given an index. `({ index: int }): any` | +| rowHeight | Number or Function | ✓ | Either a fixed row height (number) or a function that returns the height of a row given its index: `({ index: number }): number` | +| rowRenderer | Function | | Responsible for rendering a table row given an array of columns. [Learn more](#rowrenderer) | +| rowStyle | Object or Function | | Optional custom inline style to attach to table rows. This value may be either a style object or a function with the signature `({ index: number }): Object`. Note that for the header row an index of `-1` is provided. | +| scrollToAlignment | String | | Controls the alignment scrolled-to-rows. The default ("_auto_") scrolls the least amount possible to ensure that the specified row is fully visible. Use "_start_" to always align rows to the top of the list and "_end_" to align them bottom. Use "_center_" to align them in the middle of container. | +| scrollToIndex | Number | | Row index to ensure visible (by forcefully scrolling if necessary) | +| scrollTop | Number | | Vertical offset | +| sort | Function | | Sort function to be called if a sortable header is clicked. `({ defaultSortDirection: string, event: MouseEvent, sortBy: string, sortDirection: SortDirection }): void` | +| sortBy | String | | Data is currently sorted by this `dataKey` (if it is sorted at all) | +| sortDirection | [SortDirection](SortDirection.md) | | Data is currently sorted in this direction (if it is sorted at all) | +| style | Object | | Optional custom inline style to attach to root `Table` element. | +| tabIndex | Number | | Optional override of inner `Grid` tab index default; defaults to `0`. | +| width | Number | ✓ | Width of the table | ### Public Methods ##### forceUpdateGrid + Forcefully re-render the inner `Grid` component. Calling `forceUpdate` on `Table` may not re-render the inner `Grid` since it uses `shallowCompare` as a performance optimization. @@ -66,12 +67,14 @@ Gets offset for a given row and alignment. Gets the scrollbar width used to pad the table-header. ##### measureAllRows + Pre-measure all rows in a `Table`. Typically rows are only measured as needed and estimated heights are used for cells that have not yet been measured. This method ensures that the next call to getTotalSize() returns an exact size (as opposed to just an estimated one). ##### recomputeRowHeights (index: number) + Recompute row heights and offsets after the specified index (defaults to 0). `Table` has no way of knowing when its underlying list data has changed since it only receives a `rowHeight` property. @@ -94,15 +97,15 @@ This method can be used to safely scroll back to a cell that a user has scrolled The Table component supports the following static class names -| Property | Description | -|:---|:---| -| ReactVirtualized__Table | Main (outer) element | -| ReactVirtualized__Table__headerColumn | Header cell (similar to `thead > tr > th`) | -| ReactVirtualized__Table__headerRow | Header row (similar to `thead > tr`) | -| ReactVirtualized__Table__row | Table row (akin to `tbody > tr`) | -| ReactVirtualized__Table__rowColumn | Table column (akin to `tbody > tr > td`) | -| ReactVirtualized__Table__sortableHeaderColumn | Applied to header columns that are sortable | -| ReactVirtualized__Table__sortableHeaderIcon | SVG sort indicator | +| Property | Description | +| :-------------------------------------------- | :------------------------------------------ | +| ReactVirtualized\_\_Table | Main (outer) element | +| ReactVirtualized**Table**headerColumn | Header cell (similar to `thead > tr > th`) | +| ReactVirtualized**Table**headerRow | Header row (similar to `thead > tr`) | +| ReactVirtualized**Table**row | Table row (akin to `tbody > tr`) | +| ReactVirtualized**Table**rowColumn | Table column (akin to `tbody > tr > td`) | +| ReactVirtualized**Table**sortableHeaderColumn | Applied to header columns that are sortable | +| ReactVirtualized**Table**sortableHeaderIcon | SVG sort indicator | ### headerRowRenderer @@ -112,11 +115,11 @@ You may want to start by forking the [`defaultTableHeaderRowRenderer`](https://g This function accepts the following named parameters: -| Property | Description | -|:---|:---| -| className | Header class name | -| columns | Array of React nodes | -| style | Header style object | +| Property | Description | +| :-------- | :------------------- | +| className | Header class name | +| columns | Array of React nodes | +| style | Header style object | ### rowRenderer @@ -125,23 +128,18 @@ It is useful for situations where you require additional hooks into `Table` (eg If you do override `rowRenderer` the easiest way is to decorate the default implementation like so: ```jsx -import { SortableContainer, SortableElement } from 'react-sortable-hoc' -import { defaultTableRowRenderer, Table } from 'react-virtualized' +import {SortableContainer, SortableElement} from 'react-sortable-hoc'; +import {defaultTableRowRenderer, Table} from 'react-virtualized'; -const SortableTable = SortableContainer(Table) -const SortableTableRowRenderer = SortableElement(defaultTableRowRenderer) +const SortableTable = SortableContainer(Table); +const SortableTableRowRenderer = SortableElement(defaultTableRowRenderer); -function rowRenderer (props) { - return +function rowRenderer(props) { + return ; } -function CustomizedTable (props) { - return ( - - ) +function CustomizedTable(props) { + return ; } ``` @@ -149,18 +147,18 @@ If you require greater customization, you may want to fork the [`defaultTableRow This function accepts the following named parameters: -| Property | Description | -|:---|:---| -| className | Row-level class name | -| columns | Array of React nodes | -| index | Row index | -| isScrolling | Boolean flag indicating if `Table` is currently being scrolled | -| onRowClick | Optional row `onClick` handler | -| onRowDoubleClick | Optional row `onDoubleClick` handler | -| onRowMouseOver | Optional row `onMouseOver` handler | -| onRowMouseOut | Optional row `onMouseOut` handler | -| rowData | Row data | -| style | Row-level style object | +| Property | Description | +| :--------------- | :------------------------------------------------------------- | +| className | Row-level class name | +| columns | Array of React nodes | +| index | Row index | +| isScrolling | Boolean flag indicating if `Table` is currently being scrolled | +| onRowClick | Optional row `onClick` handler | +| onRowDoubleClick | Optional row `onDoubleClick` handler | +| onRowMouseOver | Optional row `onMouseOver` handler | +| onRowMouseOut | Optional row `onMouseOut` handler | +| rowData | Row data | +| style | Row-level style object | ### Examples @@ -169,12 +167,12 @@ Below is a very basic `Table` example. This table has only 2 columns, each conta ```javascript import React from 'react'; import ReactDOM from 'react-dom'; -import { Column, Table } from 'react-virtualized'; +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' } + {name: 'Brian Vaughn', description: 'Software engineer'}, // And so on... ]; @@ -186,19 +184,10 @@ ReactDOM.render( headerHeight={20} rowHeight={30} rowCount={list.length} - rowGetter={({ index }) => list[index]} - > - - + rowGetter={({index}) => list[index]}> + + , - document.getElementById('example') + document.getElementById('example'), ); ``` diff --git a/docs/WindowScroller.md b/docs/WindowScroller.md index 9736f0a0c..8f6f15212 100644 --- a/docs/WindowScroller.md +++ b/docs/WindowScroller.md @@ -1,5 +1,4 @@ -WindowScroller ---------------- +## WindowScroller A component that enables a `Table` or `List` component to be scrolled based on the window's scroll positions. This can be used to create layouts similar to Facebook or Twitter news feeds. @@ -8,24 +7,26 @@ This can be used to create layouts similar to Facebook or Twitter news feeds. This may change with a future release but for the time being this component should be used with `Table` or `List` only. ### Prop Types -| Property | Type | Required? | Description | -|:---|:---|:---:|:---| -| children | Function | ✓ | Function responsible for rendering children. This function should implement the following signature: `({ height: number, width: number, isScrolling: boolean, scrollTop: number, registerChild: function, onChildScroll: function }) => PropTypes.element` | -| onResize | Function | | Callback to be invoked on-resize; it is passed the following named parameters: `({ height: number, width: number })`. | -| onScroll | Function | | Callback to be invoked on-scroll; it is passed the following named parameters: `({ scrollTop: number, scrollLeft: number })`. | -| scrollElement | any | | Element to attach scroll event listeners. Defaults to `window`. | -| scrollingResetTimeInterval | Number | | Wait this amount of time after the last scroll event before resetting WindowScroller `pointer-events`; defaults to 150ms. | -| serverHeight | Number | | Height used for server-side rendering. | -| serverWidth | Number | | Width used for server-side rendering. | - -### Render Props -| Property | Type | Description | -|:---|:---|:---| -| height | Number | The height of the viewport. | -| isScrolling | Boolean | Indicates if the `Table` or `List` is scrolling | -| onChildScroll | Function | Used by the `Table` or `List`'s `onScroll` prop to "scroll" the list | + +| Property | Type | Required? | Description | +| :------------------------- | :------- | :-------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| children | Function | ✓ | Function responsible for rendering children. This function should implement the following signature: `({ height: number, width: number, isScrolling: boolean, scrollTop: number, registerChild: function, onChildScroll: function }) => PropTypes.element` | +| onResize | Function | | Callback to be invoked on-resize; it is passed the following named parameters: `({ height: number, width: number })`. | +| onScroll | Function | | Callback to be invoked on-scroll; it is passed the following named parameters: `({ scrollTop: number, scrollLeft: number })`. | +| scrollElement | any | | Element to attach scroll event listeners. Defaults to `window`. | +| scrollingResetTimeInterval | Number | | Wait this amount of time after the last scroll event before resetting WindowScroller `pointer-events`; defaults to 150ms. | +| serverHeight | Number | | Height used for server-side rendering. | +| serverWidth | Number | | Width used for server-side rendering. | + +### Render Props + +| Property | Type | Description | +| :------------ | :------- | :--------------------------------------------------------------------------------------------------------- | +| height | Number | The height of the viewport. | +| isScrolling | Boolean | Indicates if the `Table` or `List` is scrolling | +| onChildScroll | Function | Used by the `Table` or `List`'s `onScroll` prop to "scroll" the list | | registerChild | Function | specify grid container deeper in layout (by default `WindowScroller` uses `ReactDOM.findDOMNode` function) | -| scrollTop | Number | Scroll distance from the page | +| scrollTop | Number | Scroll distance from the page | ### Public Methods diff --git a/docs/creatingAnInfiniteLoadingList.md b/docs/creatingAnInfiniteLoadingList.md index 9b1a279ef..04ddb3101 100644 --- a/docs/creatingAnInfiniteLoadingList.md +++ b/docs/creatingAnInfiniteLoadingList.md @@ -1,12 +1,11 @@ -Creating an Infinite-Loading List ---------------- +## Creating an Infinite-Loading List The `InfiniteLoader` component was created to help break large data sets down into chunks that could be just-in-time loaded as they were scrolled into view. It can also be used to create an infinite-loading list (eg. Twitter or Facebook). Here's a basic example of how you might implement that: ```jsx -function MyComponent ({ +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.) */ @@ -14,49 +13,41 @@ function MyComponent ({ /** List of items loaded so far */ list, /** Callback function (eg. Redux action-creator) responsible for loading the next page of items */ - loadNextPage + 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 + 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 + const loadMoreRows = isNextPageLoading ? () => {} : loadNextPage; // Every row is loaded except for our loading indicator row. - const isRowLoaded = ({ index }) => !hasNextPage || index < list.size + const isRowLoaded = ({index}) => !hasNextPage || index < list.size; // Render a list item or a loading indicator. - const rowRenderer = ({ index, key, style }) => { - let content + const rowRenderer = ({index, key, style}) => { + let content; - if (!isRowLoaded({ index })) { - content = 'Loading...' + if (!isRowLoaded({index})) { + content = 'Loading...'; } else { - content = list.getIn([index, 'name']) + content = list.getIn([index, 'name']); } return ( -
+
{content}
- ) - } + ); + }; return ( - {({ onRowsRendered, registerChild }) => ( + rowCount={rowCount}> + {({onRowsRendered, registerChild}) => ( )} - ) + ); } ``` diff --git a/docs/customizingStyles.md b/docs/customizingStyles.md index c7606b7a0..bdb5732b7 100644 --- a/docs/customizingStyles.md +++ b/docs/customizingStyles.md @@ -1,5 +1,4 @@ -Customizing Classes and Styles ---------------- +## Customizing Classes and Styles React virtual CSS styles are split into their own, separately loaded stylesheet in order to simplify universal/isomorphic usage while also enabling styles to be customized. This stylesheet should be imported somewhere (usually during bootstrapping) like so: @@ -10,19 +9,23 @@ import 'react-virtualized/styles.css'; You can also customize component styles in any of the ways below: #### Forked Styles + Fork the react-virtualized `styles.css` file and load your own, totally custom styles. #### Global CSS + Load an additional, external CSS file that defines global classes (eg. `.ReactVirtualized__Table`, `.ReactVirtualized__Table__row`) to append to default inline styles. Learn more about which class names a component supports in the [API docs](https://github.com/bvaughn/react-virtualized/blob/master/docs/). #### CSS Modules + If you are using CSS modules you can specify custom class names to be appended to a component instance (eg. `Table` supports `className`, `headerClassName`, and `rowClassName` properties). Learn more about which class names are supported in the [API docs](https://github.com/bvaughn/react-virtualized/blob/master/docs/). #### Inline Styles + react-virtualized components support inline style props for style overrides. Learn more about which inline style properties are supported in the [API docs](https://github.com/bvaughn/react-virtualized/blob/master/docs/). diff --git a/docs/multiColumnSortTable.md b/docs/multiColumnSortTable.md index dbaf95061..533ae38a8 100644 --- a/docs/multiColumnSortTable.md +++ b/docs/multiColumnSortTable.md @@ -3,16 +3,9 @@ For advanced use cases, you may want to sort by multiple fields. This can be accomplished using the `createMultiSort` utility. ```jsx -import { - createTableMultiSort, - Column, - Table, -} from 'react-virtualized'; +import {createTableMultiSort, Column, Table} from 'react-virtualized'; -function sort({ - sortBy, - sortDirection, -}) { +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. @@ -23,7 +16,7 @@ const sortState = createMultiSort(sort); // When rendering your header columns, // Use the sort state exposed by sortState: -const headerRenderer = ({ dataKey, label }) => { +const headerRenderer = ({dataKey, label}) => { const showSortIndicator = sortState.sortBy.includes(dataKey); return ( <> @@ -40,16 +33,13 @@ const headerRenderer = ({ dataKey, label }) => { {...tableProps} sort={sortState.sort} sortBy={undefined} - sortDirection={undefined} -> - - + sortDirection={undefined}> + +; ``` The `createMultiSort` utility also accepts default sort-by values: + ```js const sortState = createMultiSort(sort, { defaultSortBy: ['firstName', 'lastName'], @@ -58,4 +48,4 @@ const sortState = createMultiSort(sort, { lastName: 'ASC', }, }); -``` \ No newline at end of file +``` diff --git a/docs/overscanUsage.md b/docs/overscanUsage.md index 4e5dbd570..3242508f0 100644 --- a/docs/overscanUsage.md +++ b/docs/overscanUsage.md @@ -4,4 +4,4 @@ This property has performance implications though: the higher the value, the mor I suggest using the default value (10) as a starting point and lowering it if possible. Setting the value too high will erase the performance gains achieved by using react-virtualized. You should aim to use the lowest value as possible that still generally avoids any empty space from appearing during normal scrolling actions. -Note that the same advice applies to the `overscanColumnCount` as well. \ No newline at end of file +Note that the same advice applies to the `overscanColumnCount` as well. diff --git a/docs/reverseList.md b/docs/reverseList.md index e6442efb2..2a8b752a8 100644 --- a/docs/reverseList.md +++ b/docs/reverseList.md @@ -1,5 +1,4 @@ -Displaying Items in Reverse Order ---------------- +## Displaying Items in Reverse Order Sometimes it is desirable to display a list in reverse order. The simplest way to do this is to add items to the front of the list (`unshift`) instead of the end (`push`). @@ -7,29 +6,29 @@ Here is a high level template for doing this: ```jsx export default class Example extends Component { - constructor (props) { - super(props) + constructor(props) { + super(props); this.state = { - list: [] - } + list: [], + }; } - componentDidMount () { - this._interval = setInterval(::this._updateFeed, 500) + componentDidMount() { + this._interval = setInterval(::this._updateFeed, 500); } - componentWillUnmount () { - clearInterval(this._interval) + componentWillUnmount() { + clearInterval(this._interval); } - render () { - const { list } = this.state + render() { + const {list} = this.state; return (
- ) + ); } - _updateFeed () { - const list = [ ...this.state.list ] + _updateFeed() { + const list = [...this.state.list]; - list.unshift( + list + .unshift // Add new item here - ) + (); - this.setState({ list }) + this.setState({list}); // If you want to scroll to the top you can do it like this - this.refs.List.scrollToRow(0) + this.refs.List.scrollToRow(0); } - _rowRenderer ({ key, index }) { + _rowRenderer({key, index}) { return ( -
+
{/* Your content goes here */}
- ) + ); } } ``` diff --git a/docs/tableWithNaturalSort.md b/docs/tableWithNaturalSort.md index 6841d2587..95589e668 100644 --- a/docs/tableWithNaturalSort.md +++ b/docs/tableWithNaturalSort.md @@ -10,66 +10,59 @@ Fortunately `Table` makes it easy for you to implement this functionality within ```jsx export default class NaturalSortTable extends Component { - constructor (props, context) { - super(props, context) + constructor(props, context) { + super(props, context); this.state = { - list: props.list // Naturally sorted list - } + list: props.list, // Naturally sorted list + }; } - componentWillUpdate (nextProps, nextState) { - const { - sortBy: prevSortBy, - sortDirection: prevSortDirection - } = this.state + componentWillUpdate(nextProps, nextState) { + const {sortBy: prevSortBy, sortDirection: prevSortDirection} = this.state; if ( nextState.sortBy !== prevSortBy || nextState.sortDirection !== prevSortDirection ) { - const { sortBy, sortDirection } = nextState + const {sortBy, sortDirection} = nextState; - let { list } = this.props + let {list} = this.props; if (sortBy) { - list = list.sortBy(item => item[sortBy]) + list = list.sortBy(item => item[sortBy]); if (sortDirection === SortDirection.DESC) { - list = list.reverse() + list = list.reverse(); } } } } - render () { - const { list, sortBy, sortDirection } = this.state + render() { + const {list, sortBy, sortDirection} = this.state; return ( + sortDirection={sortDirection}> {/* s go here */}
- ) + ); } - _sort ({ sortBy, sortDirection }) { - const { - sortBy: prevSortBy, - sortDirection: prevSortDirection - } = this.state + _sort({sortBy, sortDirection}) { + const {sortBy: prevSortBy, sortDirection: prevSortDirection} = this.state; // If list was sorted DESC by this column. // Rather than switch to ASC, return to "natural" order. if (prevSortDirection === SortDirection.DESC) { - sortBy = null - sortDirection = null + sortBy = null; + sortDirection = null; } - this.setState({ sortBy, sortDirection }) + this.setState({sortBy, sortDirection}); } } ``` diff --git a/docs/upgrades/Version8.md b/docs/upgrades/Version8.md index 680b819e8..0dd16f1ce 100644 --- a/docs/upgrades/Version8.md +++ b/docs/upgrades/Version8.md @@ -29,32 +29,23 @@ Due to the complexity of this change there is no codemod. However you can use th ```jsx // Can be used for Grid, List, or Table -function createCellRenderer (cellRenderer) { - console.warn('cellRenderer udpate needed') +function createCellRenderer(cellRenderer) { + console.warn('cellRenderer udpate needed'); - return function cellRendererWrapper ({ key, style, ...rest }) { + return function cellRendererWrapper({key, style, ...rest}) { return ( -
+
{cellRenderer(rest)}
- ) - } + ); + }; } // Demonstrates example usage -function renderGrid (props) { - const { cellRenderer, ...rest } = props +function renderGrid(props) { + const {cellRenderer, ...rest} = props; - return ( - - ) + return ; } ``` @@ -63,11 +54,11 @@ function renderGrid (props) { Removing the DOM wrapper for cells (and rows) means that you can now fully control a cell's styles. However this means that you'll need to audit your code to ensure that you've migrated the following properties: -| Component | Properties to be removed | -|:---|:---| -| `Grid` | `cellClassName`, `cellStyle` | -| `VirtualScroll` | `rowClassName`, `rowStyle` | -| `FlexTable` | `rowWrapperClassName`, `rowWrapperStyle` | +| Component | Properties to be removed | +| :-------------- | :--------------------------------------- | +| `Grid` | `cellClassName`, `cellStyle` | +| `VirtualScroll` | `rowClassName`, `rowStyle` | +| `FlexTable` | `rowWrapperClassName`, `rowWrapperStyle` | Here is an example: @@ -118,7 +109,7 @@ function renderGrid (props) { Typically this step will not require any action. However if you have customized react-virtualized's global styles, you'll need to be update your overrides as follows: -1. Add the prefix: _ReactVirtualized___. +1. Add the prefix: \_ReactVirtualized\_\_\_. 2. Replace _FlexTable_ with _Table_ and _VirtualScroll_ with _List_. ```css diff --git a/docs/usingAutoSizer.md b/docs/usingAutoSizer.md index 0bed95b59..49013b01e 100644 --- a/docs/usingAutoSizer.md +++ b/docs/usingAutoSizer.md @@ -1,5 +1,4 @@ -Using AutoSizer ---------------- +## Using AutoSizer The `AutoSizer` component decorates a React element and automatically manages `width` and `height` properties so that decorated element fills the available space. This simplifies usage of components like `Grid`, `Table`, and `List` that require explicit dimensions. @@ -12,6 +11,7 @@ This component uses [`javascript-detect-element-resize`](https://github.com/sdec If the parent has style `position: static` (default value), it changes to `position: relative`. It also injects a sibling `div` for size measuring. #### Why is my `AutoSizer` setting a height of 0? + `AutoSizer` expands to _fill_ its parent but it will not _stretch_ the parent. This is done to prevent problems with flexbox layouts. If `AutoSizer` is reporting a height (or width) of 0- then it's likely that the parent element (or one of its parents) has a height of 0. @@ -19,21 +19,17 @@ One easy way to test this is to add a style property (eg `background-color: red; (eg You may need to add `height: 100%` or `flex: 1` to the parent.) #### Can I use AutoSizer to manage only width or height (not both)? + You can use `AutoSizer` to control only one dimension of its child component using the `disableHeight` or `disableWidth` attributes. For example, a fixed-height component that should grow to fill the available width can be created like so: ```jsx - {({ width }) => ( - - )} + {({width}) => } ``` #### Can I use AutoSizer within a flex container? + When using an `AutoSizer` as a direct child of a flex box it usually works out best to wrap it with a div, like so: ```jsx @@ -54,13 +50,14 @@ When using an `AutoSizer` as a direct child of a flex box it usually works out b ``` #### Can I use AutoSizer with other HOCs like InfiniteLoader? + `AutoSizer` can be used within other react-virtualized HOCs such as `InfiniteLoader` or `ScrollSync` like so: ```jsx - {({ onRowsRendered, registerChild }) => ( + {({onRowsRendered, registerChild}) => ( - {({ height, width }) => ( + {({height, width}) => (