Skip to main content
Implement user blocking functionality to prevent unwanted communication in your React chat app.

Overview

The Block Users feature allows users to prevent specific users from sending them messages, effectively cutting off communication from unwanted contacts.
  • Block Users feature allows users to prevent specific users from sending them messages.
  • Provides privacy control, prevents harassment, and allows users to manage their communication preferences.
  • Your app will allow users to block/unblock other users, hide message composers for blocked users, and provide appropriate UI feedback for blocked states.

Prerequisites

  • React v18.2.0+
  • CometChat React UI Kit v6.1.0+
  • CometChat Chat SDK JavaScript v4.0.13+
  • Project setup with initialized CometChat credentials (App ID, Auth Key, Region)
  • TypeScript support (recommended)
  • User authentication and chat functionality already implemented

Components

Component / ClassRole
CometChat.blockUsers()SDK method to block specific users
CometChat.unblockUsers()SDK method to unblock previously blocked users
CometChatUserEvents.ccUserBlockedEvent listener for when a user is blocked
CometChatUserEvents.ccUserUnblockedEvent listener for when a user is unblocked
CometChatConfirmDialogConfirmation dialog for block/unblock actions
CometChatToastToast notifications for action feedback

Integration Steps

1. Block User Function Implementation

File: CometChatHome.tsx
const onBlockUserClicked: () => Promise<void> = () => {
    let UID = user.getUid();
    return new Promise(async (resolve, reject) => {
        CometChat.blockUsers([UID]).then(
            list => {
                user.setBlockedByMe(true);
                CometChatUserEvents.ccUserBlocked.next(user);
                toastTextRef.current = getLocalizedString("blocked_successfully");
                setShowToast(true);
                return resolve();
            }, error => {
                console.log("Blocking user fails with error", error);
                return reject();
            }
        )
    })
}

2. Unblock User Function Implementation

File: CometChatHome.tsx
const onUnblockUserClicked = () => {
    let UID = user.getUid();
    CometChat.unblockUsers([UID]).then(
        list => {
            setActionItems([{
                "name": getLocalizedString("user_details_block"),
                "icon": blockIcon,
                "id": "block_unblock_user"
            }, {
                "name": getLocalizedString("delete_chat"),
                "icon": deleteIcon,
                "id": "delete_chat"
            }]);
            user.setBlockedByMe(false);
            CometChatUserEvents.ccUserUnblocked.next(user);
        }, error => {
            console.log("Unblocking user fails with error", error);
        }
    );
}

3. Block User Confirmation Dialog

File: CometChatHome.tsx
const getBlockUserConfirmationDialogView = () => {
    return <>
        <div className="cometchat-block-user-dialog__backdrop">
            <CometChatConfirmDialog
                title={getLocalizedString("block_contact")}
                messageText={getLocalizedString("confirm_block_contact")}
                confirmButtonText={getLocalizedString("user_details_block")}
                onCancelClick={() => {
                    setShowBlockUserDialog(!showBlockUserDialog);
                }}
                onSubmitClick={onBlockUserClicked} />
        </div>
    </>
}

4. Message Composer Blocked State

File: CometChatMessages.tsx
{showComposerState ? (
    <div className="cometchat-composer-wrapper">
        <CometChatMessageComposer
            user={user}
            group={group}
        />
    </div>
) : (
    <div className="message-composer-blocked" onClick={() => {
        if (user) {
            CometChat.unblockUsers([user?.getUid()]).then(() => {
                user.setBlockedByMe(false);
                CometChatUserEvents.ccUserUnblocked.next(user);
            })
        }
    }}>
        <div className="message-composer-blocked__text">
            {getLocalizedString("cannot_send_to_blocked_user")} 
            <a>{getLocalizedString("click_to_unblock")}</a>
        </div>
    </div>
)}

Implementation Flow

  • Fetch Data / User State
File: CometChatHome.tsx
if (user?.getBlockedByMe?.()) {
    setShowComposerState(false);
}
  • Load Blocked Status / Associated Data
File: CometChatMessages.tsx
useEffect(() => {
    if (messageUser?.getBlockedByMe()) {
        setShowComposer(false);
    }
    const unsubscribeFromEvents = subscribeToEvents();
    return () => {
        unsubscribeFromEvents();
    };
}, [subscribeToEvents, selectedItem]);
  • Send Block/Unblock Action Handler
File: CometChatHome.tsx
const onUserActionClick = (item: { name: string; icon: string; }) => {
    if (item.name == getLocalizedString("user_details_block")) {
        setShowBlockUserDialog(true);
    } else if (item.name == getLocalizedString("user_details_unblock")) {
        onUnblockUserClicked();
    }
}
  • Live Updates / Observers
File: CometChatHome.tsx
const ccUserBlocked = CometChatUserEvents.ccUserBlocked.subscribe(user => {
    if (user.getBlockedByMe()) {
        setShowComposer(false);
    }
    updateUserAfterBlockUnblock(user);
});

const ccUserUnblocked = CometChatUserEvents.ccUserUnblocked.subscribe(user => {
    if (!user.getBlockedByMe()) {
        setShowComposer(true);
    }
    updateUserAfterBlockUnblock(user);
});

Customization Options

  • Styling overrides for blocked states and confirmation dialogs
  • Custom block/unblock confirmation messages
  • Toast notification customization
  • Custom action items for different user states
  • Custom blocked state UI

Filtering / Edge Cases

  • Detect when blocking status changes mid-chat
  • Prevent duplicate block actions
  • Handle blocked users in search results
  • Respect group chat rules when blocking
  • Keep old messages visible from blocked users

Error Handling

CometChat.blockUsers([UID]).then(
    list => {
        user.setBlockedByMe(true);
        CometChatUserEvents.ccUserBlocked.next(user);
        toastTextRef.current = getLocalizedString("blocked_successfully");
        setShowToast(true);
    }, error => {
        console.log("Blocking user fails with error", error);
    }
)
  • Handle block/unblock network errors
  • Provide retry options
  • Maintain UI consistency on errors

Context-Specific Notes

  • Blocking applies only to private chats, not groups
  • Blocked users may still appear in lists but with indicators
  • Existing messages remain visible
  • Updates are reflected in real-time

Summary / Feature Matrix

FeatureComponent / MethodFile Reference
Block userCometChat.blockUsers([UID])CometChatHome.tsx
Unblock userCometChat.unblockUsers([UID])CometChatHome.tsx
Check blocked statususer.getBlockedByMe()CometChatMessages.tsx
Block confirmation dlgCometChatConfirmDialogCometChatHome.tsx
Blocked composer statemessage-composer-blockedCometChatMessages.tsx
Block user eventsccUserBlocked.subscribe()CometChatHome.tsx
Unblock user eventsccUserUnblocked.subscribe()CometChatHome.tsx
Update user stateuser.setBlockedByMe(boolean)CometChatHome.tsx

Next Steps & Further Reading

I