Skip to content

Early previewhamur is not on npm yet. The components are being built in the open, follow along on GitHub.

LayoutReact

Infinite Scroll

A stream of content that loads more at its end, and optionally at its start, as the reader reaches it.

Rendered by React 19.3.1

import * as React from 'react'
import { InfiniteScroll } from '@hamur/react/infinite-scroll'

interface Post {
  id: number
  title: string
  body: string
}

const topics = [
  'The build now caches its dependencies between runs.',
  'A smaller bundle for the date picker, with the same API.',
  'Keyboard users can reach every control without a mouse.',
  'The release notes list what changed since the last tag.',
  'Dark mode follows the system setting unless it is overridden.',
]

function makePosts(offset: number): Post[] {
  return Array.from({ length: 10 }, (_, index) => {
    const id = offset + index + 1
    return { id, title: `Post ${id}`, body: topics[id % topics.length] }
  })
}

function fetchPosts(offset: number) {
  return new Promise<Post[]>((resolve) => setTimeout(() => resolve(makePosts(offset)), 400))
}

export default function InfiniteScrollExample() {
  const [posts, setPosts] = React.useState(() => makePosts(0))

  async function load() {
    const next = await fetchPosts(posts.length)
    setPosts((current) => [...current, ...next])
  }

  return (
    <div className="stack">
      <InfiniteScroll.Root
        className="infinite-scroll"
        hasMore={posts.length < 1000}
        onLoadMore={load}
      >
        <div className="infinite-scroll-scroller">
          <InfiniteScroll.Feed
            className="infinite-scroll-feed"
            aria-label="Posts"
          >
            {posts.map((post, index) => (
              <InfiniteScroll.Article
                key={post.id}
                className="infinite-scroll-article"
                index={index}
                aria-labelledby={`infinite-scroll-${post.id}`}
              >
                <h4 id={`infinite-scroll-${post.id}`} className="infinite-scroll-title">
                  {post.title}
                </h4>
                <p className="infinite-scroll-body">{post.body}</p>
              </InfiniteScroll.Article>
            ))}
          </InfiniteScroll.Feed>
          <InfiniteScroll.Sentinel className="infinite-scroll-edge">
            <InfiniteScroll.Loading className="infinite-scroll-status">
              Loading more posts…
            </InfiniteScroll.Loading>
          </InfiniteScroll.Sentinel>
        </div>
      </InfiniteScroll.Root>
      <p className="muted">{posts.length} posts loaded</p>
    </div>
  )
}
Not measured yetTests passing in React
14.3 KiBSize
Not measured yetMemory
Not measured yetSpeed
[N] commits

Installation

npm i @hamur/react

Not on npm yet. The package goes out under the chosen name.

Anatomy

Import the component and assemble its parts:

<InfiniteScroll.Root>
  <InfiniteScroll.Feed>
    <InfiniteScroll.Article />
  </InfiniteScroll.Feed>
  <InfiniteScroll.Sentinel>
    <InfiniteScroll.Loading />
  </InfiniteScroll.Sentinel>
</InfiniteScroll.Root>

// Not in this example: InfiniteScroll.End, InfiniteScroll.Error, InfiniteScroll.Trigger

Examples

Manual

mode="manual" with a Load more button; the second page fails once and the same button, now Try again, retries.

InfiniteScrollManual.tsx
import * as React from 'react'
import { InfiniteScroll } from '@hamur/react/infinite-scroll'

interface Post {
  id: number
  title: string
  body: string
}

const topics = [
  'The build now caches its dependencies between runs.',
  'A smaller bundle for the date picker, with the same API.',
  'Keyboard users can reach every control without a mouse.',
  'The release notes list what changed since the last tag.',
  'Dark mode follows the system setting unless it is overridden.',
]

function makePosts(offset: number): Post[] {
  return Array.from({ length: 5 }, (_, index) => {
    const id = offset + index + 1
    return { id, title: `Post ${id}`, body: topics[id % topics.length] }
  })
}

export default function InfiniteScrollManualExample() {
  const [posts, setPosts] = React.useState(() => makePosts(0))
  const [error, setError] = React.useState(false)
  const failNext = React.useRef(true)

  async function load() {
    setError(false)
    try {
      const next = await new Promise<Post[]>((resolve, reject) =>
        setTimeout(() => {
          if (failNext.current && posts.length === 5) {
            failNext.current = false
            reject(new Error('Network error'))
          } else resolve(makePosts(posts.length))
        }, 400),
      )
      setPosts((current) => [...current, ...next])
    } catch {
      setError(true)
    }
  }

  return (
    <div className="stack">
      <InfiniteScroll.Root
        className="infinite-scroll"
        mode="manual"
        error={error}
        hasMore={posts.length < 20}
        onLoadMore={load}
      >
        <div className="infinite-scroll-scroller">
          <InfiniteScroll.Feed
            className="infinite-scroll-feed"
            aria-label="Posts"
          >
            {posts.map((post, index) => (
              <InfiniteScroll.Article
                key={post.id}
                className="infinite-scroll-article"
                index={index}
                aria-labelledby={`infinite-scroll-manual-${post.id}`}
              >
                <h4 id={`infinite-scroll-manual-${post.id}`} className="infinite-scroll-title">
                  {post.title}
                </h4>
                <p className="infinite-scroll-body">{post.body}</p>
              </InfiniteScroll.Article>
            ))}
          </InfiniteScroll.Feed>
          <InfiniteScroll.Sentinel className="infinite-scroll-edge">
            <InfiniteScroll.Loading className="infinite-scroll-status">
              Loading more posts…
            </InfiniteScroll.Loading>
            <InfiniteScroll.Error className="infinite-scroll-status">
              The posts could not be loaded.
            </InfiniteScroll.Error>
            <InfiniteScroll.End className="infinite-scroll-status">
              No more posts.
            </InfiniteScroll.End>
            <InfiniteScroll.Trigger className="button infinite-scroll-trigger">
              {error ? 'Try again' : 'Load more'}
            </InfiniteScroll.Trigger>
          </InfiniteScroll.Sentinel>
        </div>
      </InfiniteScroll.Root>
    </div>
  )
}

Start

A conversation opened at its newest message: hasMoreStart and a start Sentinel load older ones above while the reading position holds.

InfiniteScrollStart.tsx
import * as React from 'react'
import { InfiniteScroll } from '@hamur/react/infinite-scroll'

interface Message {
  id: number
  author: string
  text: string
}

const authors = ['Ada', 'Grace', 'Linus']
const lines = [
  'Pushed the fix, the build is running.',
  'Can you look at the failing test?',
  'It passes here. I will rerun it.',
  'Merged. Thanks for the quick review.',
]

function makeMessages(from: number, to: number): Message[] {
  return Array.from({ length: to - from + 1 }, (_, index) => {
    const id = from + index
    return { id, author: authors[id % authors.length], text: lines[id % lines.length] }
  })
}

export default function InfiniteScrollStartExample() {
  const [messages, setMessages] = React.useState(() => makeMessages(31, 40))
  const scroller = React.useRef<HTMLDivElement>(null)

  React.useLayoutEffect(() => {
    const element = scroller.current
    if (element) element.scrollTop = element.scrollHeight
  }, [])

  async function load() {
    const first = messages[0].id
    const older = await new Promise<Message[]>((resolve) =>
      setTimeout(() => resolve(makeMessages(Math.max(1, first - 10), first - 1)), 400),
    )
    setMessages((current) => [...older, ...current])
  }

  return (
    <div className="stack">
      <InfiniteScroll.Root
        className="infinite-scroll"
        hasMore={false}
        hasMoreStart={messages[0].id > 1}
        onLoadMore={load}
      >
        <div ref={scroller} className="infinite-scroll-scroller">
          <InfiniteScroll.Sentinel
            side="start"
            className="infinite-scroll-edge"
          >
            <InfiniteScroll.Loading className="infinite-scroll-status">
              Loading older messages…
            </InfiniteScroll.Loading>
            <InfiniteScroll.End className="infinite-scroll-status">
              This is the start of the conversation.
            </InfiniteScroll.End>
          </InfiniteScroll.Sentinel>
          <InfiniteScroll.Feed
            className="infinite-scroll-feed"
            aria-label="Messages"
          >
            {messages.map((message, index) => (
              <InfiniteScroll.Article
                key={message.id}
                className="infinite-scroll-article"
                index={index}
                aria-labelledby={`infinite-scroll-start-${message.id}`}
              >
                <h4 id={`infinite-scroll-start-${message.id}`} className="infinite-scroll-title">
                  {message.author} · #{message.id}
                </h4>
                <p className="infinite-scroll-body">{message.text}</p>
              </InfiniteScroll.Article>
            ))}
          </InfiniteScroll.Feed>
        </div>
      </InfiniteScroll.Root>
      <p className="muted">{messages.length} of 40 messages loaded</p>
    </div>
  )
}

Virtualized

10,000 posts loaded 50 at a time with the Virtualizer inside the Feed; totalCount keeps each place right.

InfiniteScrollVirtualized.tsx
import * as React from 'react'
import { InfiniteScroll } from '@hamur/react/infinite-scroll'
import { Virtualizer } from '@hamur/react/virtualizer'

interface Post {
  id: number
  title: string
  body: string
}

const TOTAL = 10000
const topics = [
  'The build now caches its dependencies between runs.',
  'A smaller bundle for the date picker, with the same API.',
  'Keyboard users can reach every control without a mouse.',
  'The release notes list what changed since the last tag.',
  'Dark mode follows the system setting unless it is overridden.',
]

function makePosts(offset: number): Post[] {
  return Array.from({ length: 50 }, (_, index) => {
    const id = offset + index + 1
    return { id, title: `Post ${id}`, body: topics[id % topics.length] }
  })
}

export default function InfiniteScrollVirtualizedExample() {
  const [posts, setPosts] = React.useState(() => makePosts(0))

  async function load() {
    const next = await new Promise<Post[]>((resolve) =>
      setTimeout(() => resolve(makePosts(posts.length)), 300),
    )
    setPosts((current) => [...current, ...next])
  }

  return (
    <div className="stack">
      <InfiniteScroll.Root
        className="infinite-scroll"
        hasMore={posts.length < TOTAL}
        itemCount={posts.length}
        totalCount={TOTAL}
        onLoadMore={load}
      >
        <div className="infinite-scroll-scroller">
          <InfiniteScroll.Feed
            className="infinite-scroll-feed"
            aria-label="Posts"
          >
            <Virtualizer
              items={posts}
              getItemKey={(post: Post) => post.id}
              itemHeight={72}
              itemAria="none"
              scrollElement={null}
            >
              {(post: Post, index: number, props) => (
                <InfiniteScroll.Article
                  {...props}
                  className="infinite-scroll-article infinite-scroll-fixed"
                  index={index}
                  aria-labelledby={`infinite-scroll-virtual-${post.id}`}
                >
                  <h4 id={`infinite-scroll-virtual-${post.id}`} className="infinite-scroll-title">
                    {post.title}
                  </h4>
                  <p className="infinite-scroll-body">{post.body}</p>
                </InfiniteScroll.Article>
              )}
            </Virtualizer>
          </InfiniteScroll.Feed>
          <InfiniteScroll.Sentinel className="infinite-scroll-edge">
            <InfiniteScroll.Loading className="infinite-scroll-status">
              Loading more posts…
            </InfiniteScroll.Loading>
          </InfiniteScroll.Sentinel>
        </div>
      </InfiniteScroll.Root>
      <p className="muted">{posts.length} of 10,000 posts loaded</p>
    </div>
  )
}

End

25 posts in five pages; once the last arrives End replaces Loading and the end is announced.

InfiniteScrollEnd.tsx
import * as React from 'react'
import { InfiniteScroll } from '@hamur/react/infinite-scroll'

interface Post {
  id: number
  title: string
  body: string
}

const TOTAL = 25
const topics = [
  'The build now caches its dependencies between runs.',
  'A smaller bundle for the date picker, with the same API.',
  'Keyboard users can reach every control without a mouse.',
  'The release notes list what changed since the last tag.',
  'Dark mode follows the system setting unless it is overridden.',
]

function makePosts(offset: number): Post[] {
  return Array.from({ length: 5 }, (_, index) => {
    const id = offset + index + 1
    return { id, title: `Post ${id}`, body: topics[id % topics.length] }
  })
}

export default function InfiniteScrollEndExample() {
  const [posts, setPosts] = React.useState(() => makePosts(0))

  async function load() {
    const next = await new Promise<Post[]>((resolve) =>
      setTimeout(() => resolve(makePosts(posts.length)), 300),
    )
    setPosts((current) => [...current, ...next])
  }

  return (
    <div className="stack">
      <InfiniteScroll.Root
        className="infinite-scroll"
        hasMore={posts.length < TOTAL}
        totalCount={TOTAL}
        onLoadMore={load}
      >
        <div className="infinite-scroll-scroller">
          <InfiniteScroll.Feed
            className="infinite-scroll-feed"
            aria-label="Posts"
          >
            {posts.map((post, index) => (
              <InfiniteScroll.Article
                key={post.id}
                className="infinite-scroll-article"
                index={index}
                aria-labelledby={`infinite-scroll-end-${post.id}`}
              >
                <h4 id={`infinite-scroll-end-${post.id}`} className="infinite-scroll-title">
                  {post.title}
                </h4>
                <p className="infinite-scroll-body">{post.body}</p>
              </InfiniteScroll.Article>
            ))}
          </InfiniteScroll.Feed>
          <InfiniteScroll.Sentinel className="infinite-scroll-edge">
            <InfiniteScroll.Loading className="infinite-scroll-status">
              Loading more posts…
            </InfiniteScroll.Loading>
            <InfiniteScroll.End className="infinite-scroll-status">
              You have seen all {TOTAL} posts.
            </InfiniteScroll.End>
          </InfiniteScroll.Sentinel>
        </div>
      </InfiniteScroll.Root>
      <p className="muted">
        {posts.length} of {TOTAL} posts loaded
      </p>
    </div>
  )
}

API reference

24 props across 8 parts, in React syntax. className, style, render are listed once, under Shared props.

ArticleInfiniteScroll.Article

One item of the feed. Holds the feed's single Tab stop when it last held focus. Name it with aria-labelledby pointing at its title. Renders an <article>.

Article props
PropTypeDefault
indexThe article's 0-based place among the loaded items.number—
Article data attributes
Data attributeDescription
data-indexThe article's 0-based place among the loaded items.

EndInfiniteScroll.End

Renders its children only when its side has no more to load, such as "No more posts", or "No results" for an empty feed. Renders a <div>.

End props
PropTypeDefault
sideThe side whose state the part shows.InfiniteScrollSide'end'
End data attributes
Data attributeDescription
data-sideThe side whose state the part shows.

ErrorInfiniteScroll.Error

Renders its children only while its side's last load failed, such as a message beside the Trigger that retries. Renders a <div>.

Error props
PropTypeDefault
sideThe side whose state the part shows.InfiniteScrollSide'end'
Error data attributes
Data attributeDescription
data-sideThe side whose state the part shows.

FeedInfiniteScroll.Feed

The feed of articles: aria-busy while a side loads, and the Page Up, Page Down, Control + Home and Control + End keys. Name it with aria-label or aria-labelledby. Renders a <div>.

Feed data attributes
Data attributeDescription
data-loadingPresent while either side loads.

LoadingInfiniteScroll.Loading

Renders its children only while its side loads, such as a spinner or skeletons. Renders a <div>.

Loading props
PropTypeDefault
sideThe side whose state the part shows.InfiniteScrollSide'end'
Loading data attributes
Data attributeDescription
data-sideThe side whose state the part shows.

RootInfiniteScroll.Root

Groups an infinite scroll: a stream of content that loads more at its end, and optionally at its start, as the user reaches it. Holds both sides' state and renders the status region after its children. Renders a <div>.

Root props
PropTypeDefault
onLoadMoreCalled when a side should load more.((eventDetails: InfiniteScrollLoadDetails) => void | Promise<unknown>)—
hasMoreWhether the end side has more to load.booleantrue
loadingWhether the end side is loading.boolean—
errorWhether the end side's last load failed.boolean—
hasMoreStartWhether the start side has more to load.booleanfalse
loadingStartWhether the start side is loading.boolean—
errorStartWhether the start side's last load failed.boolean—
modeWhether a side loads when the user nears it (auto) or only from a Trigger (manual).InfiniteScrollMode'auto'
thresholdHow close, in px, a Sentinel comes to the scroller's visible edge before its side loads.number300
maxAutoLoadsThe automatic loads per side, since mount or reset(), after which the side loads only fromnumberInfinity
itemCountThe number of loaded items.number—
totalCountThe number of items there are in all, written as aria-setsize; -1 when unknown.number—
orientationThe axis the content scrolls along.InfiniteScrollOrientation'vertical'
disabledWhether no load starts.booleanfalse
labelsThe texts of the status messages.Partial<InfiniteScrollLabels>—
actionsRefA ref to imperative actions: loadMore(side) and reset().React.Ref<InfiniteScrollActions>—
Root data attributes
Data attributeDescription
data-loadingPresent while either side loads.
data-emptyPresent when no item is loaded and no side loads.
data-disabledPresent when the infinite scroll is disabled.

SentinelInfiniteScroll.Sentinel

The edge a side loads from when the user nears it, placed before the Feed (start) or after it (end), and the container of that side's Trigger, Loading, Error and End. Renders a <div>.

Sentinel props
PropTypeDefault
sideThe side the sentinel loads: start before the Feed, end after it.InfiniteScrollSide'end'
Sentinel data attributes
Data attributeDescription
data-sideThe side the sentinel loads.
data-statusThe side's status.
data-pausedPresent while the side does not load automatically: manual mode, or after maxAutoLoads.

TriggerInfiniteScroll.Trigger

A button that loads its side now, and retries after an error. Rendered only while its side has more; aria-disabled and still focusable while its side loads. Renders a <button>.

Trigger props
PropTypeDefault
sideThe side the trigger loads.InfiniteScrollSide'end'
focusableWhenDisabledWhether the button stays focusable while its side loads or the Root is disabled.booleantrue
nativeButtonWhether the component renders a native <button> element when replacing itbooleantrue
Trigger data attributes
Data attributeDescription
data-sideThe side the trigger loads.
data-loadingPresent while its side loads.
data-disabledPresent when the infinite scroll is disabled.

Shared props

Every part that renders an element takes these.

Shared props
PropType
classNameCSS class applied to the element, or a function that returns a class based on the component's state.string | ((state: State) => string | undefined)
styleStyle applied to the element, or a function that returns a style object based on the component's state.React.CSSProperties | ((state: State) => React.CSSProperties | undefined)
renderAllows you to replace the component's HTML element with a different tag, or compose it with another component.React.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, State>

Keyboard and accessibility

Keyboard

Keyboard
KeysDoesPart
Page DownMoves focus to the next Article; at the last one, loads the end side (in manual mode, focuses its Trigger)Feed
Page DownAt the last Article in manual mode, focuses the end Trigger without a loadFeed
Page UpMoves focus to the previous Article; at the first, the same for the start sideFeed
ControlEndControlHomeMoves focus to the first focusable element after or before the FeedFeed

Accessibility

What the parts set
PartSetsSo that
Roota role="status" region, polite and atomica load that runs long, an error, the new items and the end are each said once, outside the busy feed
Feedrole="feed", aria-busy="true" while a side loads, named by aria-label or aria-labelledbyassistive technology waits for the new items before it reads on
Articlearia-posinset and aria-setsize, one Tab stop (tabindex 0 on the current one, -1 on the others)the reader hears "post 11 of 25" and the page has one tab stop in the feed
Sentineldata-side and data-status, no rolethe edge can be styled by what it is doing
Triggera button with aria-disabled while its side loadsthe keyboard and screen reader path to load, retry or continue; it keeps focus while it loads
Errorrendered only while its side failedthe failure is on the page and in the status region
Endrendered only when its side has no morethe reader knows the feed is whole

Focus order

  1. Each Article is a tab stop only while it is the current one; Tab leaves the Feed for the next control, and Page Down and Page Up move between the Articles.
  2. A control inside an Article keeps its place in the tab order.
  3. The Trigger comes after the Feed (or before it, for the start side) and is reached by Tab.
  4. When a Trigger ends its own side, focus goes to the outermost Article instead of falling to the page.