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.

View as Markdown

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.

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.

Prerequisites

This guide assumes you have:

1. Create the thread panel

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

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 }}
    />
  );
}

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:

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,
};

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:

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>
);

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 and edit it as shown below:

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>

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 to count the messages in each thread.

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);
  }
}

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

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>
  );
}

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

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>

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
.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;
}