From e743bf51d9be40240763027e34f07ca663a18b63 Mon Sep 17 00:00:00 2001 From: Rom Grk Date: Wed, 30 Aug 2023 21:35:16 -0400 Subject: [PATCH] [DataGrid] Fix error when keyboard navigating an empty grid (#10081) --- .../useGridKeyboardNavigation.ts | 4 ++-- .../src/tests/keyboard.DataGrid.test.tsx | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/packages/grid/x-data-grid/src/hooks/features/keyboardNavigation/useGridKeyboardNavigation.ts b/packages/grid/x-data-grid/src/hooks/features/keyboardNavigation/useGridKeyboardNavigation.ts index bf58d31341507..4971ea0d19891 100644 --- a/packages/grid/x-data-grid/src/hooks/features/keyboardNavigation/useGridKeyboardNavigation.ts +++ b/packages/grid/x-data-grid/src/hooks/features/keyboardNavigation/useGridKeyboardNavigation.ts @@ -171,7 +171,7 @@ export const useGridKeyboardNavigation = ( const getRowIdFromIndex = React.useCallback( (rowIndex: number) => { - return currentPageRows?.[rowIndex].id; + return currentPageRows[rowIndex]?.id; }, [currentPageRows], ); @@ -197,7 +197,7 @@ export const useGridKeyboardNavigation = ( const viewportPageSize = apiRef.current.getViewportPageSize(); const colIndexBefore = params.field ? apiRef.current.getColumnIndex(params.field) : 0; - const firstRowIndexInPage = 0; + const firstRowIndexInPage = currentPageRows.length > 0 ? 0 : null; const lastRowIndexInPage = currentPageRows.length - 1; const firstColIndex = 0; const lastColIndex = gridVisibleColumnDefinitionsSelector(apiRef).length - 1; diff --git a/packages/grid/x-data-grid/src/tests/keyboard.DataGrid.test.tsx b/packages/grid/x-data-grid/src/tests/keyboard.DataGrid.test.tsx index 06f067396b145..b9a4b8cbfe453 100644 --- a/packages/grid/x-data-grid/src/tests/keyboard.DataGrid.test.tsx +++ b/packages/grid/x-data-grid/src/tests/keyboard.DataGrid.test.tsx @@ -715,4 +715,19 @@ describe(' - Keyboard', () => { fireEvent.keyDown(firstCell, { key: 'ArrowDown' }); expect(virtualScroller.scrollLeft).to.equal(0); }); + + it('should not throw when moving into an empty grid', async () => { + const columns = [{ field: 'id', width: 400 }, { field: 'name' }]; + const rows = [] as any[]; + + render( +
+ +
, + ); + + const cell = getColumnHeaderCell(0); + act(() => cell.focus()); + fireEvent.keyDown(cell, { key: 'ArrowDown' }); + }); });