---
url: https://talkjs.com/docs/Guides/Conversation_Threads/
title: "Conversation threads | Guides | TalkJS Docs"
---

For AI agents: Find a documentation index at https://talkjs.com/llms.txt (full content at https://talkjs.com/llms-full.txt). Get a markdown version of any page by appending .md to its URL path.

# Conversation threads

Keep side discussions in a reply panel beside the main chat.

You can customize TalkJS to organize replies into Slack-style threads, with a side panel beside the main chat.

![A team conversation with reply counts below messages and a panel showing a design discussion.](https://talkjs.com/docs/conversation-threads.png)

We'll keep the main chat and all of its threads in the same TalkJS conversation, using message custom data to record which thread a message belongs to:

-   The **main chat** only shows messages that don't have a `threadId`.
-   The **thread panel** only shows messages whose `threadId` matches the message you clicked.
-   Any message sent from the thread panel gets that `threadId` added automatically.

Because threads just use custom data, TalkJS's regular inline replies still work separately. If you don't want both, you can disable normal replies in your role's [**Chat UI** settings in the dashboard](https://talkjs.com/dashboard/roles/settings/default/chat-ui).

## Prerequisites

This guide assumes you have:

-   [`@talkjs/react-components`](https://www.npmjs.com/package/@talkjs/react-components) or [`@talkjs/web-components`](https://www.npmjs.com/package/@talkjs/web-components) `0.3.16` or later
-   [`@talkjs/core`](https://www.npmjs.com/package/@talkjs/core) `1.13.0` or later
-   A working TalkJS chat with an existing conversation (see the [UI Components getting started guides](https://talkjs.com/docs/UI_Components/))

## 1\. Create the thread panel

When someone opens a thread, show it to the side in its own chatbox:

**React**

```jsx
import { Chatbox } from '@talkjs/react-components';

function ThreadPanel({ appId, userId, conversationId, activeThread, onClose }) {
  return (
    <Chatbox
      appId={appId}
      userId={userId}
      conversationId={conversationId}
      // Only show this thread's messages
      messageFilter={{ custom: { threadId: ['==', activeThread.id] } }}
      // Messages sent in the side panel go to the thread, not the main chat
      beforeSendMessage={() => ({ custom: { threadId: activeThread.id } })}
      theme={threadTheme}
      themeCustom={{ activeThread, onClose }}
    />
  );
}
```

**Web Components**

```javascript
function createThreadPanel({ appId, userId, conversationId, activeThread, onClose }) {
  const thread = document.createElement('t-chatbox');
  Object.assign(thread, {
    appId,
    userId,
    conversationId,
    // Only show this thread's messages
    messageFilter: { custom: { threadId: ['==', activeThread.id] } },
    // Messages sent in the side panel go to the thread, not the main chat
    beforeSendMessage: () => ({ custom: { threadId: activeThread.id } }),
    theme: threadTheme,
    themeCustom: { activeThread, onClose },
  });
  return thread;
}
```

Now create `threadTheme` to customize how the thread panel looks, adding a close button to the header and displaying the thread's original message at the start of the message list:

**React**

```jsx
import { defaultTheme } from '@talkjs/react-components';

function ThreadHeader({ common }) {
  return (
    <div className="thread-header">
      <h2>Thread</h2>
      <button className="close-thread" aria-label="Close thread" onClick={common.themeCustom.onClose}>
        ×
      </button>
    </div>
  );
}

function OriginalMessage({ common }) {
  // The original message doesn't have threadId, so we show it manually
  return (
    <div className="t-message-group thread-original">
      <defaultTheme.Message
        common={common}
        message={common.themeCustom.activeThread}
        messageStatus="sent"
        permissions={{
          // This is just a visual placeholder, so disable messages actions
          canReplyToMessage: false,
          canEditMessage: false,
          canDeleteMessage: false,
          canAddReaction: false,
        }}
      />
    </div>
  );
}

const threadTheme = {
  ChatHeader: ThreadHeader,
  BeforeMessages: OriginalMessage,
};
```

**Web Components**

```javascript
import { html, defaultTheme } from '@talkjs/web-components';

function ThreadHeader({ common }) {
  return html`
    <div className="thread-header">
      <h2>Thread</h2>
      <button className="close-thread" aria-label="Close thread" onClick=${common.themeCustom.onClose}>
        ×
      </button>
    </div>
  `;
}

function OriginalMessage({ common }) {
  // The original message doesn't have threadId, so we show it manually
  return html`
    <div className="t-message-group thread-original">
      <${defaultTheme.Message}
        common=${common}
        message=${common.themeCustom.activeThread}
        messageStatus="sent"
        permissions=${{
          // This is just a visual placeholder, so disable messages actions
          canReplyToMessage: false,
          canEditMessage: false,
          canDeleteMessage: false,
          canAddReaction: false,
        }}
      />
    </div>
  `;
}

const threadTheme = {
  ChatHeader: ThreadHeader,
  BeforeMessages: OriginalMessage,
};
```

## 2\. Show both chatboxes side by side

Render the main chatbox beside `ThreadPanel`, filtering out messages with a `threadId` so thread replies only appear in the side panel:

**React**

```jsx
const [activeThread, setActiveThread] = useState(null);

return (
  <div className="threaded-chat">
    <div className="main-chat">
      <Chatbox
        appId={appId}
        userId={userId}
        conversationId={conversationId}
        // Hide thread replies in the main chat
        messageFilter={{ custom: { threadId: '!exists' } }}
        theme={{ Message }}
        themeCustom={{ setActiveThread }}
      />
    </div>
    {activeThread && (
      <div className="thread-panel">
        <ThreadPanel
          // Resets the thread chatbox cleanly when switching threads
          key={activeThread.id}
          appId={appId}
          userId={userId}
          conversationId={conversationId}
          activeThread={activeThread}
          onClose={() => setActiveThread(null)}
        />
      </div>
    )}
  </div>
);
```

**Web Components**

```javascript
Object.assign(chatbox, {
  appId,
  userId,
  conversationId,
  // Hide thread replies in the main chat
  messageFilter: { custom: { threadId: '!exists' } },
  theme: { Message },
  themeCustom: { setActiveThread },
});

function setActiveThread(activeThread) {
  // threadContainer is the side panel element beside your main <t-chatbox>
  if (!activeThread) {
    threadContainer.replaceChildren();
    return;
  }
  threadContainer.replaceChildren(
    createThreadPanel({ appId, userId, conversationId, activeThread, onClose: () => setActiveThread(null) })
  );
}
```

Next, create that custom `Message` component so users can start a thread on any message.

## 3\. Add a "start thread" button

We'll edit the default message component to add a "start thread" button. Download a copy from the [Message theme component docs](https://talkjs.com/docs/UI_Components/Theme/Theme_components/Message/#example) and edit it as shown below:

**React**

```jsx
+ function SpeechBubbleIcon() {
+   return (
+     <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
+       <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
+     </svg>
+   );
+ }

  export function Message(props) {
    const { message, messageStatus, permissions, common } = props;
    // ... existing Message code ...

        <div className="t-message-buttons">
          {showActionMenu && (
            <PopoverButton ... />
          )}

+         {conversation.access === 'ReadWrite' && messageStatus !== 'sending' && (
+           <button
+             className="thread-action"
+             aria-label="Reply in thread"
+             title="Reply in thread"
+             onClick={() => common.themeCustom.setActiveThread(message)}
+           >
+             <SpeechBubbleIcon />
+           </button>
+         )}

          {canAddReaction && (
            <PopoverButton ... />
          )}
        </div>
```

**Web Components**

```javascript
+ function SpeechBubbleIcon() {
+   return html`
+     <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
+       <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
+     </svg>
+   `;
+ }

  export function Message(props) {
    const { message, messageStatus, permissions, common } = props;
    // ... existing Message code ...

        <div className="t-message-buttons">
          ${showActionMenu && html`<${PopoverButton} ... />`}

+         ${conversation.access === 'ReadWrite' && messageStatus !== 'sending' && html`
+           <button
+             className="thread-action"
+             aria-label="Reply in thread"
+             title="Reply in thread"
+             onClick=${() => common.themeCustom.setActiveThread(message)}
+           >
+             <${SpeechBubbleIcon} />
+           </button>
+         `}

          ${canAddReaction && html`<${PopoverButton} ... />`}
        </div>
```

## 4\. Show live reply counts

Next, we want to show which messages already have threads, and how many messages are in each thread. We will use the [JavaScript Data API](https://talkjs.com/docs/Data_APIs/JavaScript/Conversations/#ConversationRef__subscribeMessages) to count the messages in each thread.

**React**

```jsx
import { useEffect, useRef, useState } from 'react';
import { getTalkSession } from '@talkjs/core';

// Inside your chat component:
const [replyCounts, setReplyCounts] = useState(new Map());
const subRef = useRef(null);

useEffect(() => {
  const conversation = getTalkSession({ appId, userId }).conversation(conversationId);
  const sub = conversation.subscribeMessages(
    { filter: { custom: { threadId: 'exists' } } },
    (replies) => {
      const counts = new Map();
      for (const reply of replies ?? []) {
        const id = reply.custom.threadId;
        counts.set(id, (counts.get(id) ?? 0) + 1);
      }
      setReplyCounts(counts);
    }
  );

  subRef.current = sub;
  return () => sub.unsubscribe();
}, [appId, userId, conversationId]);

function loadRepliesBefore(timestamp) {
  const sub = subRef.current;
  if (sub?.state.type !== 'active' || sub.state.loadedAll) return;
  const oldestReply = sub.state.latestSnapshot?.at(-1)?.createdAt;
  if (oldestReply && timestamp < oldestReply) {
    // TalkJS deduplicates concurrent loadMore calls for you
    sub.loadMore(100);
  }
}
```

**Web Components**

```javascript
import { getTalkSession } from '@talkjs/core';

const conversation = getTalkSession({ appId, userId }).conversation(conversationId);

const sub = conversation.subscribeMessages(
  { filter: { custom: { threadId: 'exists' } } },
  (replies) => {
    const replyCounts = new Map();
    for (const reply of replies ?? []) {
      const id = reply.custom.threadId;
      replyCounts.set(id, (replyCounts.get(id) ?? 0) + 1);
    }
    chatbox.themeCustom = { setActiveThread, replyCounts, loadRepliesBefore };
  }
);

function loadRepliesBefore(timestamp) {
  if (sub.state.type !== 'active' || sub.state.loadedAll) return;
  const oldestReply = sub.state.latestSnapshot?.at(-1)?.createdAt;
  if (oldestReply && timestamp < oldestReply) {
    // TalkJS deduplicates concurrent loadMore calls for you
    sub.loadMore(100);
  }
}
```

Pass `replyCounts` and `loadRepliesBefore` into the main chatbox via `themeCustom`, then create a `ReplyCount` component:

**React**

```jsx
import { useEffect } from 'react';

function ReplyCount({ message, common }) {
  const { setActiveThread, replyCounts, loadRepliesBefore } = common.themeCustom;

  // Replies are always newer than their parent message. If this message is older
  // than the replies we've loaded, fetch another page so its count is accurate.
  useEffect(() => {
    loadRepliesBefore?.(message.createdAt);
  }, [message.createdAt, replyCounts]);

  const count = replyCounts?.get(message.id);
  if (!count) return null;

  return (
    <button className="thread-count" onClick={() => setActiveThread(message)}>
      {count} {count === 1 ? 'reply' : 'replies'}
    </button>
  );
}
```

**Web Components**

```javascript
import { html, Preact } from '@talkjs/web-components';

function ReplyCount({ message, common }) {
  const { setActiveThread, replyCounts, loadRepliesBefore } = common.themeCustom;

  // Replies are always newer than their parent message. If this message is older
  // than the replies we've loaded, fetch another page so its count is accurate.
  Preact.useEffect(() => {
    loadRepliesBefore?.(message.createdAt);
  }, [message.createdAt, replyCounts]);

  const count = replyCounts?.get(message.id);
  if (!count) return null;

  return html`
    <button className="thread-count" onClick=${() => setActiveThread(message)}>
      ${count} ${count === 1 ? 'reply' : 'replies'}
    </button>
  `;
}
```

Finally, render `ReplyCount` next to the timestamp in your custom `Message` component:

**React**

```jsx
  export function Message(props) {
    const { message, messageStatus, permissions, common } = props;
    // ... existing Message code ...

        <div className="t-message-status">
          <Timestamp timestamp={message.createdAt} common={common} />
          {senderType == 'currentUser' && <StatusTick {...props} />}
+         <ReplyCount message={message} common={common} />
        </div>
```

**Web Components**

```javascript
  export function Message(props) {
    const { message, messageStatus, permissions, common } = props;
    // ... existing Message code ...

        <div className="t-message-status">
          <${Timestamp} timestamp=${message.createdAt} common=${common} />
          ${senderType == 'currentUser' && html`<${StatusTick} ...${props} />`}
+         <${ReplyCount} message=${message} common=${common} />
        </div>
```

## 5\. Style the layout and thread controls

Load these styles after the TalkJS default stylesheet to put the main chat and thread panel side by side and style the thread header, close button, and reply counts.

Layout and thread styles

```css
.threaded-chat {
  display: flex;
  width: 100%;
  height: 100%;
  background: white;
}

.main-chat,
.thread-panel {
  min-width: 0;
  min-height: 0;
  display: flex;
}

.main-chat {
  flex: 1;
}

.thread-panel {
  flex: 0 0 42%;
  border-left: 1px solid #e3e7ee;
}

.threaded-chat .t-chatbox,
.threaded-chat t-chatbox {
  display: block;
  width: 100%;
  height: 100%;
}

/* Override TalkJS's default `svg { fill: currentColor }` so the speech bubble stays an outline */
.t-message-buttons .thread-action svg {
  fill: none;
}

/* Give system messages an actions column so the thread button isn't clipped */
.t-theme-message[t-sender="system"]:has(.thread-action) {
  grid-template-columns: minmax(0, 1fr) auto;
  grid-template-rows: auto auto;
  grid-template-areas:
    "message actions"
    "status  .";
}

.t-theme-message[t-sender="system"]:has(.thread-action):not(:first-child):not(:has(.thread-count)) {
  grid-template-rows: auto;
  grid-template-areas: "message actions";
}

/* Space the reply count beside the timestamp, and keep the status row visible on threaded messages */
.t-theme-message .t-message-status {
  align-items: center;
  gap: 8px;
}

.t-theme-message:has(.thread-count) .t-message-status {
  display: inline-flex;
}

.t-theme-message .thread-count {
  padding: 0;
  border: 0;
  background: transparent;
  color: #2563eb;
  font-size: 1em;
  font-weight: 600;
  cursor: pointer;
}

/* Place the reply count to the left of the timestamp on your own messages */
.t-theme-message[t-sender="currentUser"] .thread-count {
  order: -1;
}

.t-theme-message .thread-count:hover {
  text-decoration: underline;
}

.thread-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 18px;
  border-bottom: 1px solid #e3e7ee;
}

.thread-header h2 {
  margin: 0;
  font: 600 16px/1.5 system-ui, sans-serif;
  color: #172033;
}

.thread-header .close-thread {
  display: grid;
  place-items: center;
  width: 34px;
  height: 34px;
  padding: 0;
  border: 0;
  border-radius: 6px;
  background: transparent;
  color: #64748b;
  font-size: 26px;
  line-height: 1;
  cursor: pointer;
}

.thread-header .close-thread:hover {
  background: #f1f5f9;
}

.thread-original {
  padding-bottom: 12px;
  margin-bottom: 12px;
  border-bottom: 1px solid #e3e7ee;
}
```
