Skip to content

Allow custom list wrappers to use ul elements - #1497

Merged
petyosi merged 3 commits into
petyosi:mainfrom
cpruijsen:fix/issue-864
Sep 20, 2026
Merged

petyosi merged 3 commits into
petyosi:mainfrom
cpruijsen:fix/issue-864

Conversation

@cpruijsen

@cpruijsen cpruijsen commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Why

A custom List wrapper could render a ul at runtime, but Components['List'] fixed its forwarded ref to HTMLDivElement. Correctly typed ul wrappers therefore required a cast.

What changes

Components and GridComponents now accept an optional list-element type restricted to HTMLDivElement or HTMLUListElement. The default remains HTMLDivElement, while a ul wrapper can opt in with Components<Data, Context, HTMLUListElement>['List']. Its forwarded ref remains typed as HTMLUListElement.

Existing Item and ItemProps types are unchanged. This is a type-only change with no runtime behavior change.

Compatibility

Existing div wrappers, inline forwardRef wrappers, explicit <Virtuoso<Data, Context>> usage, and non-div item wrappers continue to compile. At the Virtuoso components-prop boundary, the list host type is intentionally not inferred so existing inline wrappers keep their current inference behavior. Separately typed list wrappers retain strict ref checking.

Fixes #864.

Annotating a custom List or Item as Components['List'] / Components['Item']
pinned the forwarded ref to HTMLDivElement, so ul/li wrappers failed to type-check.
@changeset-bot

changeset-bot Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: d99119f

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
react-virtuoso Patch
@virtuoso.dev/examples Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@petyosi

petyosi commented Sep 11, 2026

Copy link
Copy Markdown
Owner

@cpruijsen this will, however, lose the typechecking of the ref value, right? I will be able to call non-existent methods on it.

@cpruijsen

Copy link
Copy Markdown
Contributor Author

Yes, you're right, and that's a real cost. CustomComponentHostElement is any, so the ref is unchecked and calling a method that does not exist compiles.

I tried the two narrower options before settling, and only one of them works:

React.RefAttributes<HTMLElement> does not. RefObject<T> has a mutable current, so it is invariant, and ForwardedRef<HTMLElement> is not assignable to Ref<HTMLUListElement>. Every non-div case in the test file fails.

Threading the host element through Components does work, and keeps full checking:

export interface Components<Data = unknown, Context = unknown, ListEl extends HTMLElement = HTMLDivElement, ItemEl extends HTMLElement = HTMLDivElement> {
  Item?: React.ComponentType<ItemProps<Data, ItemEl> & ContextProp<Context>>
  List?: React.ComponentType<ListProps<ListEl> & ContextProp<Context>>
}

Callers then write Components<unknown, unknown, HTMLUListElement>['List'] for a ul, and plain Components['List'] still defaults to HTMLDivElement, so nothing existing breaks. I checked this against tsgo --noEmit: the ul case passes with the ref fully typed, and a bogus method on it is still an error.

The cost is two more type parameters on Components, plus the same on GridComponents and TableComponents for parity, and anyone using a non-div has to name the element.

That is an API call rather than a bug fix, so I would rather you pick. Say the word and I will switch this PR to the generic version, or keep any if you would rather not grow the signature.

@petyosi

petyosi commented Sep 17, 2026

Copy link
Copy Markdown
Owner

The generic approach has a backward-compatibility problem once the new host-element type parameters are threaded through VirtuosoProps and the exported Virtuoso signature.

This existing usage compiles with the current types but fails with the proposed generics:

<Virtuoso
  data={[{ id: 1 }]}
  components={{
    List: React.forwardRef((props, ref) => (
      <div {...props} ref={ref} />
    )),
  }}
/>

I checked this with TypeScript against the actual source declarations, applying the proposed changes in memory. Adding defaulted host-element generics changes contextual inference for the inline forwardRef: the compiler inferred ForwardRefExoticComponent<RefAttributes<null>> in this case and rejected its assignment to the List slot. Defaulting the new parameters to HTMLDivElement does not preserve this previously valid usage.

Changing only Components is insufficient: a typed ul wrapper then fails when passed to <Virtuoso components={...}>, because the component's props still use the default div types. Fully propagating the generics makes separately typed ul/li wrappers work, but introduces the inline div regression above.

There is also an annotation cost for callers who specify <Virtuoso<Data, Context>>: omitted host parameters take their defaults rather than being inferred, so custom hosts require additional explicit type arguments.

The existing div regression is the blocker for treating this generic version as a backward-compatible patch. We would need to preserve that inference or treat this as a breaking API change. These checks already used React 19 types; raising the React peer dependency alone would not fix it.

Components and GridComponents take ListEl/ItemEl parameters defaulting to
HTMLDivElement, so a wrapper annotates its own host element and keeps the ref
fully checked. Virtuoso and VirtuosoGrid accept the components object at any
host type, which keeps an inline forwardRef over a div inferring as before and
adds no type arguments at the call site. TableRow is typed as a table row.
@cpruijsen

Copy link
Copy Markdown
Contributor Author

Reproduced, same error: ForwardRefExoticComponent<RefAttributes<null>>. The
inline forwardRef has nothing to infer the host element from, so it collapses.

The problem is the parameter being inferable at the Virtuoso boundary. Keep
ListEl/ItemEl on Components/GridComponents and type the prop as
Components<Data, Context, any, any> and you get:

  • your inline div case compiles, on Virtuoso and VirtuosoGrid
  • so does <Virtuoso<{ id: number }, string>> with no extra type arguments, so
    the annotation cost you mentioned doesn't come up
  • Components<unknown, unknown, HTMLUListElement>['List'] on a ul compiles with
    the ref typed
  • ref.current.thisMethodDoesNotExist() is an error again

typecheck, lint and format are clean and the 203 tests pass.

The tradeoff: Components['List'] alone no longer types a ul, you write the
longer form. If you'd rather keep the short spelling and live with the unchecked
ref, I'll go back to the previous commit.

@petyosi

petyosi commented Sep 18, 2026

Copy link
Copy Markdown
Owner

I think there is a backward-compatible way forward if we narrow this to the original List problem.

Could you change the PR in this direction?

  • Add a defaulted ListEl generic restricted to HTMLDivElement | HTMLUListElement.
  • Keep HTMLDivElement as the default, so existing Components<Data, Context>['List'] usage keeps its current behavior.
  • Allow a ul wrapper through the explicit form Components<Data, Context, HTMLUListElement>['List'], with the ref fully checked as HTMLUListElement.
  • Apply the equivalent change to GridComponents.List.
  • Do not add ref to ItemProps and do not otherwise change Item in this PR.
  • Make no runtime changes.

The ItemProps part currently introduces a concrete compatibility regression. This existing pattern compiles on main but fails on this branch because the spread props now contain ref?: Ref<HTMLDivElement> and cannot be applied to an <li>:

const LiItem: Components<Row>['Item'] = ({
  children,
  context: _context,
  item: _item,
  ...props
}) => <li {...props}>{children}</li>

Please keep type coverage for:

  • an existing annotated div list
  • an existing inline forwardRef list
  • existing <Virtuoso<Data, Context>> usage
  • an existing non-div item that spreads its props, as above
  • the new explicitly typed ul list

This gives the original issue a sensible opt-in solution while preserving existing source behavior. Supporting typed refs for arbitrary Item hosts can be considered separately as a breaking API change.

Add a defaulted `ListEl` parameter to `Components` and `GridComponents`,
constrained to `HTMLDivElement | HTMLUListElement`. `Components<Data, Context>`
keeps its current behaviour; a `ul` wrapper opts in through
`Components<Data, Context, HTMLUListElement>['List']` with the forwarded ref
still checked.

Revert the `ItemProps` change: `Item` is untouched, so an item component that
spreads its props onto a non-div element compiles as before.

`VirtuosoProps.components` is typed `Components<Data, Context, any>` so that
`ListEl` is not inferable at the `Virtuoso` boundary. An inline `forwardRef`
list has nothing to infer the host element from, and would otherwise collapse
to `RefAttributes<null>`.

No runtime changes.
@cpruijsen

Copy link
Copy Markdown
Contributor Author

Narrowed as you asked, pushed as d99119f.

Components now takes ListEl extends HTMLDivElement | HTMLUListElement = HTMLDivElement, and the
same on GridComponents. ItemProps is back to what it is on main, so Item is untouched and your
prop-spreading <li> compiles again. No runtime change.

One caveat you should decide on, because it is the part I am least comfortable with.
VirtuosoProps.components is typed Components<Data, Context, any> rather than
Components<Data, Context>. That is what keeps your inline forwardRef case working: the moment
ListEl is inferable at the Virtuoso boundary the inline component has nothing to infer the host
element from and collapses to RefAttributes<null> again.

The cost is narrow but real. At that one call site, an inline List with an explicitly wrong ref
type is no longer rejected:

const BogusRefList = React.forwardRef<{ nonsense: true }, React.ComponentProps<NonNullable<Components['List']>>>(
  function BogusRefList({ style, children }) {
    return <div style={style}>{children}</div>
  }
)

<Virtuoso data={data} components={{ List: BogusRefList }} />

That compiles on this branch. Assigning BogusRefList straight to Components['List'] still errors
with TS2322, so the hole is at the JSX prop, not in the type itself.

I tried the obvious non-any alternative, Components<Data, Context, HTMLDivElement | HTMLUListElement>.
It does catch the bogus case, but the ref is contravariant, so a ul-typed List no longer fits the
slot, and four of your own examples that pass a div-typed Components stop compiling
(grouped-endless-scrolling, grouped-load-more, scroll-element-grid-scroller, window-grid).
I did not find a cheaper option that keeps all five cases you listed.

If you would rather not have any in that position, the fallback is to ship only the type change and
leave the prop strict. People could then annotate a ul wrapper but not pass it to <Virtuoso>,
which mostly defeats the point, so I would rather you make that call than guess again.

test/componentTypes.test-d.tsx covers the five cases: annotated div list, inline forwardRef
list, <Virtuoso<Row, unknown>>, the prop-spreading <li> item, and the typed ul on both
Virtuoso and VirtuosoGrid. It also asserts the ul ref stays narrowed rather than widening to
any. I checked that assertion fails if ListEl is not threaded into List, so it is a real guard
and not decoration.

typecheck, lint and format are clean on packages/react-virtuoso and the 203 tests pass.

@petyosi petyosi changed the title fix: allow custom List and Item refs on any HTML element Allow custom list wrappers to use ul elements Sep 20, 2026
@petyosi
petyosi merged commit ac8a5f4 into petyosi:main Sep 20, 2026
@github-actions github-actions Bot mentioned this pull request Sep 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Components["List"] expects the ref to be an HTMLDivElement in Typescript [BUG]

2 participants