petyosi / react-virtuoso

The most powerful virtual list component for React
https://virtuoso.dev
MIT License
5.32k stars 306 forks source link

[BUG] can't set initialTopMostItemIndex to undefined #1155

Closed tstehr closed 4 weeks ago

tstehr commented 4 weeks ago

Hi 👋 ,

first of all thank you for the great work with Virtuoso! I've been using the library for a few years now. I found it really easy to adapt to deal with performance problems with long lists, and also love the way I can customize all of the behaviors to fit my requirements.

Describe the bug

I'm trying to set initialTopMostItemIndex based on whether an external variable is set as follows, with activeItemIndex having a type of number | undefined.

<Virtuoso
  initialTopMostItemIndex={
    activeItemIndex
      ? { index: activeItemIndex }
      : undefined
  }
/>

However, that leads to the following error:

Screenshot 2024-11-06 at 13 10 49

Reproduction

https://codesandbox.io/p/sandbox/competent-glade-gv4pfj?file=%2Fsrc%2FApp.tsx

To Reproduce

Steps to reproduce the behavior:

  1. Click the "Re-render and toggle initialTopMostItemIndex" button in the CodeSandbox preview
  2. See the error appear in the browser console

Expected behavior

Setting initialTopMostItemIndex={undefined} should behave identical to the prop not being present at all. These are not strictly equivalent in JS terms, but given that the TypeScript typings for the component allow setting the prop to undefined it's quite unexpected for that to lead to an immediate crash.

Desktop:

Additional context

For now I'm using the following workaround to ensure the prop is unset when the variable it depends on is set to undefined:

<Virtuoso
  {...(activeItemIndex !== undefined
    ? {
      initialTopMostItemIndex: { index: activeItemIndex },
    }
    : {})}
/>
petyosi commented 4 weeks ago

Duplicate. I do understand the convenience of passing undefined, but internally this is quite the hassle to deal with. The approach you've outlined is correct. https://github.com/petyosi/react-virtuoso/issues/777

tstehr commented 3 weeks ago

Oh, I somehow failed to see the issue this duplicates. Thank you for the explanation!