Search code examples
reactjsreact-virtualizedreact-window

react-window spacing between items list


I am trying to integrate react-window with react-window-infinite-loader and so far, I have been successful, but facing an issue where I couldn't find a way to style my list item to create more spacing between the list item.

Here is my code below

export default function AutoComplete({}: AutoCompleteProps) {
  //testdata length is 35000
  const LOADING = 1;
  const LOADED = 2;

  const isItemLoaded = (index) => testData[index]?.loading === LOADED;
  const loadMoreItems = (startIndex, stopIndex) => {
    for (let index = startIndex; index <= stopIndex; index++) {
      testData[index].loading = LOADING;
    }
    return new Promise<void>((resolve) =>
      setTimeout(() => {
        for (let index = startIndex; index <= stopIndex; index++) {
          testData[index].loading = LOADED;
        }
        resolve();
      }, 2500)
    );
  };
  const Row = ({ index, style }) => {
    let label;
    if (testData[index].loading === LOADED) {
      label = `${testData[index].title}`;
    } else {
      label = "Loading...";
    }
    const listStyle = { ...style };
    return (
      <div
        className={`whitespace-nowrap overflow-hidden text-ellipsis`}
        style={style}
      >
        <div>{label}</div>
      </div>
    );
  };

  return (
    <InfiniteLoader
      isItemLoaded={isItemLoaded}
      itemCount={testData.length}
      loadMoreItems={loadMoreItems}
    >
      {({ onItemsRendered, ref }) => (
        <List
          style={{ position: "absolute", width: "100%", marginTop: 50 }}
          className="absolute top-[110%] z-50 bg-white w-full"
          height={250 - 40}
          itemCount={testData.length}
          itemSize={30}
          width={300}
          onItemsRendered={onItemsRendered}
          ref={ref}
        >
          {({ index, style }) => <Row index={index} style={style} />}
        </List>
      )}
    </InfiniteLoader>
  );
}

The output is shared here as you can see the list items are very close to each other and I need to add some padding maybe to make it look cleaner.


Solution

  • Increasing the value of <List></List>'s height prop and proportionately increasing the value of the itemSize prop will solve the problem. Here's a sandbox for your reference: https://codesandbox.io/s/cold-glade-hcgy8q?file=/src/App.js

    Also, you can read about the props mentioned in the docs here: https://react-window.vercel.app/#/api/FixedSizeList

    Good luck!