Skip to main content
Version: Next

Overview

The @abpjs/chat package provides real-time messaging components and services for ABP React applications. This is the React equivalent of Angular's @volo/abp.ng.chat module.

npm version

ABP Commercial License Required

This package is free to use but requires the corresponding backend module from ABP Commercial. You can purchase an ABP Commercial license from abp.io.

Installation

npm install @abpjs/chat
# or
yarn add @abpjs/chat

Required peer dependencies:

npm install @abpjs/core @abpjs/theme-shared @chakra-ui/react @microsoft/signalr

Features

  • Real-time Messaging - SignalR-powered instant messaging
  • Contact Management - Search and filter contacts
  • Conversation History - Paginated message history
  • Unread Message Tracking - Badge with unread count
  • Message Read Receipts - Double-check mark for read messages
  • Component Replacement - Customizable components via keys

Main Exports

Components

ComponentDescription
ChatMain chat interface with contacts sidebar and conversation view
ChatContactsContacts list with search and filtering
ChatIconChat icon button with unread message badge
ConversationAvatarUser avatar with initials fallback

Hooks

HookDescription
useChatComplete chat state management hook

Services

ServiceDescription
ContactServiceREST API service for contact operations
ConversationServiceREST API service for conversation operations
ChatConfigServiceSignalR connection and real-time messaging

Constants

ConstantDescription
CHAT_ROUTE_PATHDefault chat route path (/chat)
CHAT_API_BASEChat API base path (/api/chat)
CHAT_HUB_PATHSignalR hub path (/signalr-hubs/chat)

Quick Example

import { Chat, useChat } from '@abpjs/chat';
import { useRest, useAuth } from '@abpjs/core';

function ChatPage() {
const { rest } = useRest();
const { getAccessToken } = useAuth();

const {
contacts,
selectedContact,
userMessages,
unreadMessageCount,
contactsLoading,
messagesLoading,
selectContact,
sendMessage,
loadMoreMessages,
markAsRead,
} = useChat({
rest,
getAccessToken,
hubUrl: '/signalr-hubs/chat',
});

return (
<Chat
contacts={contacts}
userMessages={userMessages}
selectedContact={selectedContact}
unreadMessageCount={unreadMessageCount}
contactsLoading={contactsLoading}
messagesLoading={messagesLoading}
onSelectContact={selectContact}
onSendMessage={sendMessage}
onLoadMore={loadMoreMessages}
onMarkAsRead={markAsRead}
/>
);
}

useChat Hook

The useChat hook manages all chat state and operations:

Options

OptionTypeDefaultDescription
restRestServicerequiredRestService instance for API calls
getAccessToken() => string | Promise<string>requiredFunction to get access token for SignalR
hubUrlstring'/signalr-hubs/chat'SignalR hub URL
includeOtherContactsbooleantrueInclude contacts without previous messages
maxResultCountnumber20Messages per page

Return Values

PropertyTypeDescription
contactsChatContactDto[]List of all contacts
selectedContactChatContactDto | nullCurrently selected contact
userMessagesMap<string, ChatMessageDto[]>Messages map keyed by user ID
unreadMessageCountnumberTotal unread message count
contactsLoadingbooleanWhether contacts are loading
messagesLoadingbooleanWhether messages are loading
allMessagesLoadedbooleanWhether all messages are loaded (pagination complete)
selectContact(contact) => voidSelect a contact to chat with
sendMessage(userId, message) => PromiseSend a message
loadMoreMessages(userId) => PromiseLoad more messages (pagination)
markAsRead(userId) => PromiseMark conversation as read
refreshContacts() => PromiseRefresh contacts list
chatConfigServiceChatConfigServiceService instance for advanced usage

Chat Component Props

PropTypeDefaultDescription
contactsChatContactDto[]requiredAll contacts to display
userMessagesMap<string, ChatMessageDto[]>requiredMessages map keyed by user ID
selectedContactChatContactDto | null-Currently selected contact
onSelectContact(contact) => void-Callback when a contact is selected
onSendMessage(userId, message) => void-Callback when sending a message
onLoadMore(userId) => void-Callback when loading more messages
onMarkAsRead(userId) => void-Callback when marking as read
unreadMessageCountnumber0Total unread message count
contactsLoadingbooleanfalseWhether contacts are loading
messagesLoadingbooleanfalseWhether messages are loading
allMessagesLoadedbooleanfalseWhether all messages loaded
sendOnEnterbooleantrueSend message on Enter key
classNamestring-Optional CSS class name

ChatIcon Component

Display a chat icon with unread message badge:

import { ChatIcon } from '@abpjs/chat';

function Header() {
return (
<ChatIcon
unreadCount={5}
onClick={() => navigate('/chat')}
/>
);
}

ChatIcon Props

PropTypeDefaultDescription
unreadCountnumber0Unread message count for badge
onClick() => void-Click handler
size'sm' | 'md' | 'lg''md'Icon size
classNamestring-Optional CSS class name

ChatConfigService

The ChatConfigService manages SignalR connections:

import { getChatConfigService } from '@abpjs/chat';

const chatConfig = getChatConfigService(rest, getAccessToken);

// Initialize SignalR
await chatConfig.initSignalR('/signalr-hubs/chat');

// Listen for incoming messages
const unsubscribe = chatConfig.onMessage((message) => {
console.log('New message:', message.text);
});

// Listen for unread count changes
chatConfig.onUnreadCountChange((count) => {
console.log('Unread count:', count);
});

// Check connection state
if (chatConfig.isConnected()) {
console.log('Connected to chat hub');
}

// Stop connection
await chatConfig.stopSignalR();

ChatConfigService Methods

MethodDescription
initSignalR(hubUrl)Initialize SignalR connection
stopSignalR()Stop SignalR connection
onMessage(callback)Subscribe to incoming messages
onUnreadCountChange(callback)Subscribe to unread count changes
setTotalUnreadMessageCount()Fetch and set total unread count
updateUnreadCount(count)Update unread count
incrementUnreadCount(amount)Increment unread count
decrementUnreadCount(amount)Decrement unread count
isConnected()Check if connected
getConnectionState()Get SignalR connection state

Models

ChatContactDto

interface ChatContactDto {
userId: string;
name: string;
surname: string;
username: string;
lastMessageSide: number; // 1=Sender, 2=Receiver
lastMessage: string;
lastMessageDate: Date | string;
unreadMessageCount: number;
}

ChatMessageDto

interface ChatMessageDto {
message: string;
messageDate: Date | string;
isRead: boolean;
readDate: Date | string;
side: ChatMessageSide; // 1=Sender, 2=Receiver
}

ChatMessage (SignalR)

interface ChatMessage {
senderUserId: string;
senderUserName: string;
senderName: string;
senderSurname: string;
text: string;
}

Enums

ChatMessageSide

import { ChatMessageSide } from '@abpjs/chat';

ChatMessageSide.Sender // 1
ChatMessageSide.Receiver // 2

Component Keys

import { eChatComponents } from '@abpjs/chat';

eChatComponents.Chat // 'Chat.ChatComponent'
eChatComponents.ChatContacts // 'Chat.ChatContactsComponent'
eChatComponents.ConversationAvatar // 'Chat.ConversationAvatarComponent'
eChatComponents.ChatIcon // 'Chat.ChatIconComponent'

Route Names

import { eChatRouteNames } from '@abpjs/chat';

eChatRouteNames.Chat // 'Chat::Menu:Chat'

TypeScript Support

import type {
ChatContactDto,
ChatMessageDto,
ChatMessage,
ChatMessageSide,
ChatProps,
ChatContactsProps,
ChatIconProps,
ConversationAvatarProps,
UseChatOptions,
UseChatReturn,
ChatComponentKey,
ChatRouteNameKey,
} from '@abpjs/chat';

Required Policies

The chat module requires the following ABP policies:

PolicyDescription
Chat.MessagingSend and receive messages

Dependencies

  • @abpjs/core - Core ABP React functionality
  • @abpjs/theme-shared - Shared UI components
  • @chakra-ui/react - UI component library
  • @microsoft/signalr - SignalR client for real-time messaging

See Also