diff --git a/packages/lib/src/spatial-navigation/components/virtualizedList/helpers/getNumberOfItemsVisibleOnScreen.ts b/packages/lib/src/spatial-navigation/components/virtualizedList/helpers/getNumberOfItemsVisibleOnScreen.ts index edb9aaff..2f9fc5c0 100644 --- a/packages/lib/src/spatial-navigation/components/virtualizedList/helpers/getNumberOfItemsVisibleOnScreen.ts +++ b/packages/lib/src/spatial-navigation/components/virtualizedList/helpers/getNumberOfItemsVisibleOnScreen.ts @@ -9,16 +9,20 @@ const getMinSizeOfItems = ({ return itemSize; } - let minSize: number | undefined = undefined; - - for (let i = 0; i < data.length; i++) { - const item = data[i]; - if (item !== undefined) { - const currentSize = itemSize(item); - if (minSize === undefined || currentSize < minSize) { - minSize = currentSize; - } - } + if (data.length === 0) { + return 0; + } + + const firstElementSize = itemSize(data[0]); + + const minSize = data.reduce((smallestSize, item) => { + const currentSize = itemSize(item); + if (currentSize < smallestSize) return currentSize; + return smallestSize; + }, firstElementSize); + + if (minSize === 0) { + console.warn('The size of the smallest item in the list is 0. The list will appear empty.'); } return minSize; @@ -33,11 +37,20 @@ export const getNumberOfItemsVisibleOnScreen = ({ listSizeInPx: number; itemSize: number | ((item: T) => number); }) => { + if (data.length === 0) { + return 0; + } + const itemSizeToComputeRanges = getMinSizeOfItems({ data, itemSize }); if (!itemSizeToComputeRanges) { return 0; } + if (itemSizeToComputeRanges === 0) { + console.warn('The size of the smallest item in the list is 0. The list will appear empty.'); + return 0; + } + return Math.floor(listSizeInPx / itemSizeToComputeRanges); };