diff --git a/README.md b/README.md index bebfafbd..d0d1e449 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,20 @@ This may be used to (re)scroll a row into view.

overscanCount

How many additional rows to render outside of the visible area. This can reduce visual flickering near the edges of a list when scrolling.

+ + + + rowKey +

By default, lists will use an item's index as its +key. +This is okay if:

+ +

If your list does not satisfy the above constraints, +use this property to specify your own keys for items.

diff --git a/lib/components/list/List.tsx b/lib/components/list/List.tsx index ae150296..00903077 100644 --- a/lib/components/list/List.tsx +++ b/lib/components/list/List.tsx @@ -37,6 +37,7 @@ export function List< rowComponent: RowComponentProp, rowCount, rowHeight: rowHeightProp, + rowKey, rowProps: rowPropsUnstable, tagName = "div" as TagName, style, @@ -185,7 +186,7 @@ export function List< "aria-setsize": rowCount, role: "listitem" }} - key={index} + key={rowKey ? rowKey(index, rowProps) : index} index={index} style={{ position: "absolute", @@ -206,6 +207,7 @@ export function List< getCellBounds, isDynamicRowHeight, rowCount, + rowKey, rowProps, startIndexOverscan, stopIndexOverscan diff --git a/lib/components/list/types.ts b/lib/components/list/types.ts index ebcbbc1a..6f778faf 100644 --- a/lib/components/list/types.ts +++ b/lib/components/list/types.ts @@ -134,6 +134,22 @@ export type ListProps< | ((index: number, cellProps: RowProps) => number) | DynamicRowHeight; + // TODO add documentation, examples, tests, whatever else, + // and implement this for grid. + // Also check whether the `PureComponent` part still applies. + /** + * By default, lists will use an item's index as its + * [key](https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key). + * This is okay if: + * - Your collections of items is never sorted or modified + * - Your item renderer is not stateful and does not extend + * `PureComponent` + * + * If your list does not satisfy the above constraints, + * use this property to specify your own keys for items. + */ + rowKey?: (index: number, data: RowProps) => React.Key; + /** * Additional props to be passed to the row-rendering component. * List will automatically re-render rows when values in this object change. diff --git a/public/generated/docs/List.json b/public/generated/docs/List.json index 9b414ca7..5832751c 100644 --- a/public/generated/docs/List.json +++ b/public/generated/docs/List.json @@ -135,6 +135,19 @@ "name": "rowHeight", "required": true }, + "rowKey": { + "description": [ + { + "content": "

By default, lists will use an item's index as its\nkey.\nThis is okay if:

\n\n" + }, + { + "content": "

If your list does not satisfy the above constraints,\nuse this property to specify your own keys for items.

\n" + } + ], + "html": "
rowKey?: (index: number, data: RowProps) => Key
", + "name": "rowKey", + "required": false + }, "rowProps": { "description": [ {