Skip to content

shadcn.io is an independent project built on shadcn/ui

Components

Free

Message Scroller for React

A chat transcript scroller for React on Base UI: each new question settles near the top, a streamed reply can be followed, and history loads in place.

On this page14 sections

Message Scroller is the scrolling part of a chat transcript. The row you mark as the start of a turn, usually the question just sent, settles near the top of the view with the end of the previous answer above it, and the reply grows into the space below. Older messages loaded above don't move what the reader is looking at.

For a log read once from the top, a Scroll Area is enough. The rows themselves come from Message and Bubble.

Preview width

Installation

Sign in to get your install command
Free with an account. It carries your token, so the CLI installs everything in one go.

Anatomy

Message Scroller anatomy: root, viewport, content, item, button

Usage

import {
  MessageScroller, MessageScrollerButton, MessageScrollerContent,
  MessageScrollerItem, MessageScrollerProvider, MessageScrollerViewport,
} from "@/components/ui/message-scroller";

MessageScroller fills its parent, so the parent needs a height. Wrap every row in MessageScrollerItem with a stable messageId, and add scrollAnchor to the row that starts a turn.

<div className="h-96">
  <MessageScrollerProvider>
    <MessageScroller>
      <MessageScrollerViewport>
        <MessageScrollerContent className="gap-4 p-4">
          <MessageScrollerItem messageId="question-1" scrollAnchor>
            Which plan includes audit logs?
          </MessageScrollerItem>
          <MessageScrollerItem messageId="answer-1">
            Audit logs come with the Business plan and above.
          </MessageScrollerItem>
        </MessageScrollerContent>
      </MessageScrollerViewport>
      <MessageScrollerButton />
    </MessageScroller>
  </MessageScrollerProvider>
</div>

In a full-height chat, make the chat's container a flex column and give MessageScroller, or the element that wraps it, the classes min-h-0 flex-1, so it takes the room left above the prompt input.

Accessibility

MessageScrollerViewport is a focusable region labeled Messages, so Tab reaches the transcript and the browser's own scroll keys work on it. Pressing one of them, turning the wheel or dragging on a touch screen tells the scroller the reader has taken over, and it stops following. MessageScrollerContent is a log that reports added rows, not text growing inside a row, so set aria-busy on it while a reply streams, as the demos do. The jump button is labeled Scroll to end or Scroll to start and turns inert while there is nothing in its direction. Pass aria-label to the viewport when Messages doesn't name your thread.

Tab
Moves focus to the transcript, then through anything focusable inside it, then to the jump button while it is active.
Arrow Down
When the transcript has focus, scrolls it down a short step.
Arrow Up
When the transcript has focus, scrolls it up a short step.
Page Down
When the transcript has focus, scrolls down by about the height of the view.
Page Up
When the transcript has focus, scrolls up by about the height of the view.
Space
When the transcript has focus, scrolls down by about the height of the view. On the jump button, presses it.
Shift+Space
When the transcript has focus, scrolls up by about the height of the view.
Home
When the transcript has focus, scrolls to the oldest loaded message.
End
When the transcript has focus, scrolls to the newest message.
Enter
When the jump button has focus, scrolls the transcript to that edge.

Demos

Anchoring

Each press of the send button adds the next message of a scripted thread, and the rows whose role is selected carry scrollAnchor. With User picked, every question settles near the top with its answer below. Switch to Assistant at any point and the thread stays, while each answer sent from then on lands at the top instead. Anchor whichever row people come back to read.

Preview width

Group chat

A thread between Grace, an agent and Rocky, where the next turn opens with an event. Add Rocky appends a "Rocky has joined the chat" marker that carries scrollAnchor, so the marker settles near the top, and Send Message as Rocky puts his reply under it. Anchor a join or handoff marker when it is what opens the next exchange.

Preview width

Previous context

The slider sets scrollPreviousItemPeek, how many pixels of the last answer stay above a new question, from 64 to 128. Send after moving it and the question settles that far down, plus the 24 pixels of scrollMargin this demo sets and the transcript's padding. Raise the peek when follow-up questions point at the end of the last answer, such as a list or a code block.

Preview width

Streaming

The same chat with autoScroll on the provider. A question still settles near the top first, and once the reply grows past the bottom edge the view follows it down. Scroll up mid-reply with the wheel, touch or a key and the view stays where you left it. Following resumes once you scroll back to the bottom or press the jump button.

Preview width

Opening position

A saved four-message thread that can open on its first message, its last line or its last question. The tabs replay each landing with the scroll commands, while in your app defaultScrollPosition on the provider does it once, on load. Pick last-anchor for long answers, so the reader sees their question and where the reply begins rather than its final paragraph.

Preview width

Load history

An incident thread that opens on its last five messages. Load History adds the five before them above, and the row you were reading stays put, because preserveScrollOnPrepend on the viewport is on by default and holds the first visible row that has a messageId. Use this for paged history in a long-running chat.

Preview width

Animation

Seven entrances for a sent message, from Fade to Spring Bounce, picked in the footer. Each is a set of animate-in classes on the user's MessageScrollerItem that changes only transform, opacity and blur, so the row's layout stays the same while it plays. Under reduced motion the row appears in place. Animating height or margin instead would move the layout the scroller measures on every frame.

Preview width

Commands

A Jump to menu in the card's header, outside MessageScroller but inside the provider, lists the four questions of an onboarding analytics thread. Choosing one calls scrollToMessage with that row's messageId, the start alignment and a smooth scroll, so the question lands at the top. Build a table of contents, search results or a permalink handler the same way.

Preview width

Visibility

Four bars beside the card stand for the four questions in an incident handoff, and the bar of the one being read is drawn darker. currentAnchorId from useMessageScrollerVisibility names that question, and it stays current while its long answer fills the view. Hover the bars to open the outline, then pick a question to jump to it.

Preview width

Scrollable

Twelve checkpoint messages that open at the top, with a footer sentence that changes as you scroll: only down at the first message, both ways in between, only up at the last. It reads start and end from useMessageScrollerScrollable. To style the scroller itself, target its data-scrollable attribute, which needs no React state, as State does.

Preview width

State

Two chips over a twelve-message transcript, Older above and Newer below, light up from the data-scrollable attribute the scroller writes on its root, through in-data-[scrollable~=start] and in-data-[scrollable~=end] classes. The demo calls no hook, so scrolling rerenders none of its own components. Use the attribute for edge shadows or hints that only need CSS, and the hook in Scrollable when your code has to act on it.

Preview width

Hooks

import {
  useMessageScroller,
  useMessageScrollerScrollable,
  useMessageScrollerVisibility,
} from "@/components/ui/message-scroller";

const { scrollToMessage, scrollToEnd, scrollToStart } = useMessageScroller();
const { start, end } = useMessageScrollerScrollable();
const { currentAnchorId, visibleMessageIds } = useMessageScrollerVisibility();

The hooks read MessageScrollerProvider, so they work anywhere under it, including a header or sidebar outside the MessageScroller frame. scrollToMessage takes align (start unless you pass another), behavior and scrollMargin, which falls back to the provider's. scrollToEnd and scrollToStart read only behavior. All three default it to auto, an instant jump, while the jump button scrolls smoothly. scrollToMessage returns false when rows are mounted and none has that id. When no row has mounted yet, it keeps the id and scrolls once that row arrives, which suits a permalink opened before the thread loads.

start and end say whether there is more to scroll to above and below. While autoScroll is following a reply, end stays false. currentAnchorId is the id of the last anchored row the reader has scrolled to, and visibleMessageIds lists the rows with a messageId that are in view, in order. The visibility observer only runs while a component calls its hook.

Avoiding a flash on reload

A scroll container always opens at the top, and HTML can't set scrollTop. With defaultScrollPosition at end, its default, or at last-anchor, the viewport carries data-pending-scroll until that position is applied, and the installed styles keep it invisible meanwhile. A server-rendered transcript is therefore blank until JavaScript runs, instead of showing its oldest messages and jumping.

To show the end on the first paint, add an inline script right after the viewport that scrolls it to the bottom and removes the attribute.

const scrollToEndScript = `(function () {
  var viewport = document.getElementById("messages");
  if (!viewport) {
    return;
  }
  viewport.scrollTop = viewport.scrollHeight;
  viewport.removeAttribute("data-pending-scroll");
})()`;

<MessageScroller>
  <MessageScrollerViewport id="messages" suppressHydrationWarning>
    <MessageScrollerContent>{/* transcript */}</MessageScrollerContent>
  </MessageScrollerViewport>
  <script dangerouslySetInnerHTML={{ __html: scrollToEndScript }} />
  <MessageScrollerButton />
</MessageScroller>

Put the script in your page, not in the component. It only works for end and only when the messages are in the server HTML, so skip it when they load on the client. Keep suppressHydrationWarning on the viewport, and pass a nonce if your Content Security Policy requires one.

AI SDK

The demos play scripted replies on a timer. With the AI SDK, useChat gives you the same two things, the messages and a status. Map the messages to items, anchor the user's, and mark the log busy while a reply streams.

"use client";

import { useChat } from "@ai-sdk/react";
import { DefaultChatTransport } from "ai";

import { Bubble, BubbleContent } from "@/components/ui/bubble";
import { Message, MessageContent } from "@/components/ui/message";
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller";

export function Chat() {
  const { messages, status } = useChat({
    transport: new DefaultChatTransport({ api: "/api/chat" }),
  });

  return (
    <MessageScrollerProvider autoScroll defaultScrollPosition="last-anchor">
      <MessageScroller>
        <MessageScrollerViewport>
          <MessageScrollerContent aria-busy={status === "streaming"}>
            {messages.map((message) => (
              <MessageScrollerItem
                key={message.id}
                messageId={message.id}
                scrollAnchor={message.role === "user"}
              >
                <Message align={message.role === "user" ? "end" : "start"}>
                  <MessageContent>
                    <Bubble variant={message.role === "user" ? "muted" : "ghost"}>
                      <BubbleContent>
                        {message.parts.map((part, index) =>
                          part.type === "text" ? (
                            <span key={`${message.id}-${index}`}>{part.text}</span>
                          ) : null
                        )}
                      </BubbleContent>
                    </Bubble>
                  </MessageContent>
                </Message>
              </MessageScrollerItem>
            ))}
          </MessageScrollerContent>
        </MessageScrollerViewport>
        <MessageScrollerButton />
      </MessageScroller>
    </MessageScrollerProvider>
  );
}

Your Prompt Input calls sendMessage from the same hook. Each question it sends is an anchor, so it settles near the top while its answer streams below.

Performance

Scrolling never rerenders your rows. The scroller keeps its position, anchoring and follow state outside React and writes it to data-* attributes on the root and the viewport, and only the components that call a hook rerender when it changes. Each MessageScrollerItem has content-visibility: auto with a 10rem placeholder size, so the browser skips laying out and painting rows far off screen while they stay in the DOM for find in page, selection and screen readers.

Virtualization

Virtualization stays outside the component. When a transcript grows past what real rows can carry, use MessageScrollerViewport as the virtualizer's scroll element and let the virtualizer own the rows. The jump button and the scroll state keep working. Anchoring, holding your place on prepend and visibility tracking don't, because they read the MessageScrollerItem rows that sit directly in the content.

import { useVirtualizer } from "@tanstack/react-virtual";
import { type ReactNode, useRef } from "react";

import { Message } from "@/components/ui/message";
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller";

export function VirtualizedTranscript({
  messages,
}: {
  messages: { id: string; content: ReactNode }[];
}) {
  const viewportRef = useRef<HTMLDivElement>(null);

  const virtualizer = useVirtualizer({
    count: messages.length,
    estimateSize: () => 86,
    getItemKey: (index) => messages[index]?.id ?? index,
    getScrollElement: () => viewportRef.current,
    overscan: 8,
  });

  return (
    <MessageScrollerProvider>
      <MessageScroller>
        <MessageScrollerViewport ref={viewportRef}>
          <MessageScrollerContent className="block min-h-full">
            <div
              className="relative w-full"
              style={{ height: virtualizer.getTotalSize() }}
            >
              {virtualizer.getVirtualItems().map((virtualItem) => {
                const message = messages[virtualItem.index];

                if (!message) {
                  return null;
                }

                return (
                  <div
                    className="absolute start-0 top-0 w-full"
                    data-index={virtualItem.index}
                    key={virtualItem.key}
                    ref={virtualizer.measureElement}
                    style={{ transform: `translateY(${virtualItem.start}px)` }}
                  >
                    <Message>{message.content}</Message>
                  </div>
                );
              })}
            </div>
          </MessageScrollerContent>
        </MessageScrollerViewport>
        <MessageScrollerButton />
      </MessageScroller>
    </MessageScrollerProvider>
  );
}

FAQ

How do I keep a new chat question at the top of a Message Scroller?

Add scrollAnchor to the MessageScrollerItem that starts the turn, usually the user's message. When a new anchored row is appended, the scroller brings it to scrollMargin plus scrollPreviousItemPeek below the top of the view, 64 pixels unless you change them, and any top padding on MessageScrollerContent adds to that. A spacer below lets it get there before the reply exists.

The reply then fills that space. Rows without the prop are never brought to the top, and anchoring follows the prop rather than the role, so a marker can open a turn too, as in Group chat.

How do I make a Message Scroller auto-scroll as a reply streams in React?

Add autoScroll to MessageScrollerProvider, which leaves it off unless you do. The view then follows the reply while the reader is at the bottom, and the wheel, a touch drag or a scroll key hands control back to them. Dragging the scrollbar doesn't count while a reply still fills the space under an anchored question: the scroller puts the question back in place.

Reaching the bottom again, pressing the jump button or calling scrollToEnd starts following once more. When the question is anchored, it holds near the top first, and following takes over once the reply reaches the bottom edge, as the Streaming demo shows.

How do I scroll a Message Scroller to a specific message from a menu or link?

Call scrollToMessage from useMessageScroller in any component under MessageScrollerProvider, even one outside the MessageScroller frame, and pass the row's messageId. Options set the alignment, the scroll behavior and a margin, as in the Commands demo.

It returns false when rows are mounted but none has that id, which is your cue to load more history and try again. Called before any row mounts, it keeps the id and scrolls once that row arrives, which suits a permalink opened while the thread is still loading.

Why does my Message Scroller grow with its messages instead of scrolling?

The scroller fills its parent, so a parent with no height grows with the content and the viewport never overflows. Give an ancestor a fixed height, or make the page a flex column and give MessageScroller, or the element that wraps it, the classes min-h-0 flex-1.

MessageScroller already carries min-h-0, but a wrapper between it and the flex column needs it too. Without it, a flex child refuses to shrink below its content and pushes the prompt input off screen. Each demo on this page sits in a card with a fixed height for the same reason.

How do I load older messages into a Message Scroller without the view jumping?

Prepend the rows, and preserveScrollOnPrepend, which the viewport has on by default, holds the reader's place. The scroller keeps track of the first visible row that has a messageId, and once rows land above it, it restores that row's offset, so the text being read doesn't move.

Rows without a messageId can't serve as that reference. To load the next page when the reader reaches the top, watch start from useMessageScrollerScrollable turn false. The Load history demo prepends five messages from a button.

Why is my server-rendered Message Scroller blank until the page loads?

With defaultScrollPosition at end, its default, or at last-anchor, the viewport carries data-pending-scroll until that position is applied in the browser, and the installed styles hide the viewport while it is set. That stops the oldest messages from flashing before the jump, at the cost of a blank transcript until JavaScript runs.

Opening at start needs no wait. For end, the inline script in Avoiding a flash on reload scrolls the viewport and removes the attribute before the first paint.

How do I open a saved chat at the last question instead of the very bottom?

Set defaultScrollPosition to last-anchor on MessageScrollerProvider. The transcript then opens with the last anchored row near the top and the previous turn peeking above it, so the reader starts at their question and the beginning of its answer.

It falls back to the bottom when no row is anchored or the last turn already fits in the view. The position is applied when rows are first there to measure, and again if the prop changes. Opening position compares it with start and end.

Is a Message Scroller accessible to keyboard and screen reader users?

The viewport is a focusable region named Messages, so keyboard users can Tab to it and scroll with the arrow keys, Page Up, Page Down, Home and End, and any of those stops auto-scrolling. The jump button is a real button named Scroll to end or Scroll to start, and it leaves the tab order while it has nowhere to go.

The content is a log that announces added rows rather than every streamed word. Set aria-busy on MessageScrollerContent while a reply streams, as the demos do, so the log is marked as mid-update.

API Reference

MessageScroller

<div> data-slot="message-scroller"

PropType
className?string

Merged with the part's classes.

AttributeType
data-autoscrolling?string

Present while the viewport is programmatically scrolling to the latest message.

data-pending-scroll?string

Present until defaultScrollPosition ("end" or "last-anchor") is applied, or skipped for an empty transcript. Hide the viewport while it is set.

data-scrollable?"start" | "end" | "start end"

Edges the viewport can scroll toward. Query one with [data-scrollable~="end"]; absent means it fits.

Type
"start" | "end" | "start end"

MessageScrollerButton

<button> data-slot="message-scroller-button"

PropType
behavior?ScrollBehavior

Native scroll behavior used when the button scrolls to its target edge.

Default
"smooth"
children?React.ReactNode

Custom button content. Defaults to the scroll icon and accessible label.

direction?"start" | "end"

Transcript edge the button scrolls toward.

Type
"start" | "end"
Default
"end"
size?"default" | "icon" | "icon-lg" | "icon-md" | "icon-sm" | "icon-xl" | "icon-xs" | "lg" | "md" | "sm" | "xl" | "xs"

Button's default: md.

Type
"default" | "icon" | "icon-lg" | "icon-md" | "icon-sm" | "icon-xl" | "icon-xs" | "lg" | "md" | "sm" | "xl" | "xs"
Default
"icon-sm"
variant?"default" | "destructive" | "ghost" | "link" | "outline" | "secondary"

Button's default: default.

Type
"default" | "destructive" | "ghost" | "link" | "outline" | "secondary"
Default
"secondary"
render?ReactElement | ((props: object, state: object) => ReactElement)

Custom render target. Its function's state has active and direction.

Type
ReactElement | ((props: object, state: object) => ReactElement)
Default
<Button />
className?string

Merged with the part's classes.

AttributeType
data-active"true" | "false"

Whether this button can currently scroll.

Type
"true" | "false"
data-direction"start" | "end"

Mirrors direction.

Type
"start" | "end"
data-size?string

Mirrors size.

data-variant?string

Mirrors variant.

MessageScrollerContent

<div> data-slot="message-scroller-content"

PropType
aria-busy?boolean

Marks the live region busy while a turn streams, if needed.

aria-relevant?string

Live-region updates to announce. Defaults to new transcript rows only.

Default
"additions"
role?string

ARIA role applied to the message list for live announcements.

Default
"log"
spacerClassName?string

Class name for the internal spacer used to make room for anchored rows.

className?string

Merged with the part's classes.

MessageScrollerItem

<div> data-slot="message-scroller-item"

PropType
messageId?string

Stable row id used by scrollToMessage, visibility, and prepend preservation.

scrollAnchor?boolean

Marks this row as a turn boundary that can anchor newly appended turns.

Default
false
className?string

Merged with the part's classes.

AttributeType
data-message-id?string

Mirrors messageId when provided.

data-scroll-anchor"true" | "false"

Mirrors scrollAnchor.

Type
"true" | "false"

MessageScrollerViewport

<div> data-slot="message-scroller-viewport"

PropType
aria-label?string

Accessible name for the scrollable chat transcript.

Default
"Messages"
preserveScrollOnPrepend?boolean

Keep the first visible message item stable when older rows are prepended.

Default
true
role?string

Landmark role for the labelled scrollable transcript viewport.

Default
"region"
tabIndex?number

Makes the transcript viewport keyboard-scrollable.

Default
0
className?string

Merged with the part's classes.

AttributeType
data-autoscrolling?string

Present while the viewport is programmatically scrolling to the latest message.

data-pending-scroll?string

Present until defaultScrollPosition ("end" or "last-anchor") is applied, or skipped for an empty transcript. Hide the viewport while it is set.

data-scrollable?"start" | "end" | "start end"

Edges the viewport can scroll toward. Query one with [data-scrollable~="end"]; absent means it fits.

Type
"start" | "end" | "start end"

MessageScrollerProvider

PropType
autoScroll?boolean

Follow new content only while the reader is already at the live edge. Wheel, touch, keyboard scroll, and explicit jumps release it.

Default
false
defaultScrollPosition?"start" | "end" | "last-anchor"

Opening position on the first non-empty render, applied once. "last-anchor" opens at the last scrollAnchor row and falls back to "end" when the turn fits or no anchor exists. For "end" and "last-anchor", the viewport has data-pending-scroll until the position is applied.

Type
"start" | "end" | "last-anchor"
Default
"end"
scrollEdgeThreshold?number

Distance from either edge that still counts as being at the start or end. Controls state attributes and scroll button visibility.

Default
8
scrollMargin?number

Margin applied to the aligned edge for scrollToMessage, visibility, and programmatic targets.

Default
0
scrollPreviousItemPeek?number

Extra margin added to scrollMargin when a newly appended scrollAnchor item is positioned so part of the previous item stays visible.

Default
64

useMessageScroller

MethodType
scrollToEnd(options?: MessageScrollerScrollOptions) → boolean

Scroll to the latest message.

Type
(options?: MessageScrollerScrollOptions) → boolean
Parameters

options? – { align?: MessageScrollerScrollAlign; behavior?: ScrollBehavior; scrollMargin?: number }

Returns
boolean
scrollToMessage(messageId: string, options?: MessageScrollerScrollOptions) → boolean

Scroll to a mounted message id.

Type
(messageId: string, options?: MessageScrollerScrollOptions) → boolean
Parameters

messageId – string

options? – { align?: MessageScrollerScrollAlign; behavior?: ScrollBehavior; scrollMargin?: number }

Returns
boolean
scrollToStart(options?: MessageScrollerScrollOptions) → boolean

Scroll to the top.

Type
(options?: MessageScrollerScrollOptions) → boolean
Parameters

options? – { align?: MessageScrollerScrollAlign; behavior?: ScrollBehavior; scrollMargin?: number }

Returns
boolean

useMessageScroller options

OptionType
align?"start" | "center" | "end" | "nearest"

How a message target aligns in the viewport.

Type
"start" | "center" | "end" | "nearest"
Default
"start"
behavior?ScrollBehavior

Native scroll behavior for the command.

Default
"auto"
scrollMargin?number

Margin applied to the aligned edge for this command. Defaults to the provider scrollMargin.

useMessageScrollerScrollable

ValueType
endboolean

Whether the viewport can scroll toward the end. Content is hidden below (!end means at the bottom). Stays false while follow-output is keeping the reader at the live edge.

startboolean

Whether the viewport can scroll toward the start. Content is hidden above (!start means at the top).

useMessageScrollerVisibility

ValueType
currentAnchorIdstring | null

The current anchored turn, based on the last scrollAnchor item at or above the reading line.

Type
string | null
visibleMessageIdsstring[]

Message ids intersecting the viewport, in document order.