Branch

PreviousNext

The Branch component manages multiple versions of AI messages, allowing users to navigate between different response branches. It provides a clean, modern interface with customizable themes and keyboard-accessible navigation buttons.

branch-default

Installation

pnpm dlx dlx shadcn@latest add https://ui.dalim.in/r/styles/default/branch.json

Usage

import {
  Branch,
  BranchMessages,
  BranchNext,
  BranchPage,
  BranchPrevious,
  BranchSelector,
} from '@/components/ai-elements/branch';
<Branch defaultBranch={0}>
  <BranchMessages>
    <Message from="user">
      <MessageContent>Hello</MessageContent>
    </Message>
    <Message from="user">
      <MessageContent>Hi!</MessageContent>
    </Message>
  </BranchMessages>
  <BranchSelector from="user">
    <BranchPrevious />
    <BranchPage />
    <BranchNext />
  </BranchSelector>
</Branch>

Usage with AI SDK

Branching is an advanced use case that you can implement yourself to suit your application's needs. While the AI SDK does not provide built-in support for branching, you have full flexibility to design and manage multiple response paths as required.

Features

  • Context-based state management for multiple message branches
  • Navigation controls for moving between branches (previous/next)
  • Uses CSS to prevent re-rendering of branches when switching
  • Branch counter showing current position (e.g., "1 of 3")
  • Automatic branch tracking and synchronization
  • Callbacks for branch change and navigation using onBranchChange
  • Support for custom branch change callbacks
  • Responsive design with mobile-friendly controls
  • Clean, modern styling with customizable themes
  • Keyboard-accessible navigation buttons

<Branch />

PropTypeDescription
defaultBranchnumberThe index of the branch to show by default (default: 0).
onBranchChange(branchIndex: number) => voidCallback fired when the branch changes.
...propsReact.HTMLAttributes<HTMLDivElement>Any other props are spread to the root div.

<BranchMessages />

PropTypeDescription
...propsReact.HTMLAttributes<HTMLDivElement>Any other props are spread to the root div.

<BranchSelector />

PropTypeDescription
fromUIMessage["role"]Aligns the selector for user, assistant or system messages.
...propsReact.HTMLAttributes<HTMLDivElement>Any other props are spread to the selector container.

<BranchPrevious />

PropTypeDescription
...propsReact.ComponentProps<typeof Button>Any other props are spread to the underlying shadcn/ui Button component.

<BranchNext />

PropTypeDescription
...propsReact.ComponentProps<typeof Button>Any other props are spread to the underlying shadcn/ui Button component.

<BranchPage />

PropTypeDescription
...propsReact.HTMLAttributes<HTMLSpanElement>Any other props are spread to the underlying span element.