Skip to content

Commit

Permalink
add row key
Browse files Browse the repository at this point in the history
  • Loading branch information
Tibs7777 committed May 10, 2022
1 parent d7d9351 commit ebce381
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/components/DataSheetGrid.tsx
Expand Up @@ -76,6 +76,7 @@ export const DataSheetGrid = React.memo(
headerRowHeight = rowHeight,
gutterColumn,
stickyRightColumn,
rowKey,
addRowsComponent: AddRowsComponent = AddRows,
createRow = DEFAULT_CREATE_ROW as () => T,
autoAddRow = false,
Expand Down Expand Up @@ -1631,6 +1632,28 @@ export const DataSheetGrid = React.memo(
[headerRowHeight, rowHeight]
)

const itemKey = useCallback(
(index: number, { data }: ListItemData<T>): React.Key => {
if (rowKey && index > 0) {
const row = data[index - 1]
if (typeof rowKey === 'function') {
return rowKey(row, index)
} else if (
typeof rowKey === 'string' &&
row instanceof Object &&
rowKey in row
) {
const key = row[rowKey as keyof T]
if (typeof key === 'string' || typeof key === 'number') {
return key
}
}
}
return index
},
[rowKey]
)

useImperativeHandle(ref, () => ({
activeCell: getCellWithId(activeCell, columns),
selection: getSelectionWithId(
Expand Down Expand Up @@ -1740,6 +1763,7 @@ export const DataSheetGrid = React.memo(
height={displayHeight}
itemCount={data.length + 1}
itemSize={itemSize}
itemKey={itemKey}
estimatedItemSize={rowHeight}
itemData={itemData}
outerRef={outerRef}
Expand Down
2 changes: 2 additions & 0 deletions src/components/StaticDataSheetGrid.tsx
Expand Up @@ -16,6 +16,7 @@ export const StaticDataSheetGrid = React.forwardRef<
createRow,
duplicateRow,
style,
rowKey,
onFocus,
onBlur,
onActiveCellChange,
Expand All @@ -33,6 +34,7 @@ export const StaticDataSheetGrid = React.forwardRef<
createRow,
duplicateRow,
style,
rowKey,
onFocus,
onBlur,
onActiveCellChange,
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Expand Up @@ -166,6 +166,7 @@ export type DataSheetGridProps<T> = {
columns?: Partial<Column<T, any, any>>[]
gutterColumn?: SimpleColumn<T, any> | false
stickyRightColumn?: SimpleColumn<T, any>
rowKey?: string | ((rowData: T, index: number) => string)
height?: number
rowHeight?: number
headerRowHeight?: number
Expand Down

0 comments on commit ebce381

Please sign in to comment.