Mention users
Tag users in chat messages with @ mentions. Type @ followed by at least three letters to see username suggestions.
Generic referencing
Channel references, user mentions, and links are MessageElement instances with different mentionType values.
Configuration options:
- User source: channel members or all app users
- Suggestions: up to 100 usernames (default: 10)
- Username length: up to 200 characters
- Mentions per message: up to 100 (default: 10)
Implementation follows similar patterns to channel referencing and links.
Requires App Context
Enable App Context in the Admin Portal to mention users.
Interactive demo
See user mentions and channel references in action with this React demo.
Want to implement something similar?
Test it out
Type in @Mar or @Man in the input field and select one of the suggested users to mention.
Add user mentions
Add user mentions with @ followed by at least three letters (e.g., @Mar).
Mentioned users are stored in the MessageDraft object. When sent with send(), mention data is saved to message metadata.
Method signature
You can add a user reference by calling the addMention() method with the target of MentionTarget.user.
Refer to the addMention() method for details.
Sample code
Create the Hello Alex! I have sent you this link on the #offtopic channel. message where Alex is a user mention.
1// Create a message draft
2messageDraft = channel.createMessageDraft({ userSuggestionSource: "global" })
3
4// Add initial text
5messageDraft.update("Hello Alex!")
6
7// Add a user mention to the string "Alex"
8messageDraft.addMention(6, 4, "mention", "alex_d")
Remove user mentions
removeMention() removes a user mention from a draft message.
Method signature
You can remove user mentions from a draft message by calling the removeMention() method at the exact offset where the user mention starts.
Refer to the removeMention() method for details.
Offset value
Provide the exact offset position where the mention starts; otherwise, it won't be removed.
Sample code
Remove the user mention from the Hello Alex! I have sent you this link on the #offtopic channel. message where Alex is a user mention.
1// assume the message reads
2// Hello Alex! I have sent you this link on the #offtopic channel.`
3
4// remove the channel reference
5messageDraft.removeMention(6)
Send message with mentions
send() publishes the text message with mentioned users and emits events of type mention.
Method signature
Head over to the Drafts documentation for details on the method signature, input, and output parameters.
Sample code
Send the previously drafted message in which you mention users @James, Sarah and @Twain, Mark.
1// Create a new MessageDraft instance with the suggested user source as "channel"
2const messageDraft = channel.createMessageDraft({
3 userSuggestionSource: "channel"
4});
5
6// Change the text
7messageDraft.update("Hello @James, Sara and @Twain, Mark.")
8
9// Add first user mention
10messageDraft.addMention(7, 12, "mention", "sarah_j")
11
12// Add second user mention
13messageDraft.addMention(24, 12, "mention", "twain_m")
14
15messageDraft.send().then((response) => {
show all 19 linesShow mention as link
getMessageElements() renders user mentions as clickable links in published messages. Create custom functions to customize rendering.
Also used for plain/text links and channel references.
Method signature
Head over to the Links documentation for details on the method signature, input, and output parameters.
Sample code
Show all linked mentions in a message as clickable links.
1message.getMessageElements()
Other examples
Customize mention rendering with these examples.
Add company links
Add a link to a PubNub profile under each user mention.
- React
- React Native
- Vue
- Angular
1const renderMessagePart = (messagePart: MixedTextTypedElement) => {
2 if (messagePart.type === "mention") {
3 // assuming messagePart.content.id is the user ID
4 const pubnubProfileUrl = `https://pubnub.com/profiles/${messagePart.content.id}`;
5 return (
6 <span>
7 <a href={pubnubProfileUrl}>{messagePart.content.name}</a>
8 {" "}
9 {/* add a space after the user mention */}
10 </span>
11 );
12 }
13 return "";
14}
1import React from 'react';
2import { Text, Linking, View } from 'react-native';
3
4const renderMessagePart = (messagePart) => {
5 if (messagePart.type === "mention") {
6 const pubnubProfileUrl = `https://pubnub.com/profiles/${messagePart.content.id}`;
7 return (
8 <View>
9 <Text>
10 <Text onPress={() => Linking.openURL(pubnubProfileUrl)}>
11 {messagePart.content.name}
12 </Text>
13 {" "}
14 </Text>
15 </View>
show all 20 lines1<template>
2 <div>
3 <span v-for="messagePart in messageParts" :key="messagePart.content.id">
4 <template v-if="messagePart.type === 'mention'">
5 <a :href="getPubnubProfileUrl(messagePart.content.id)">{{ messagePart.content.name }}</a>
6 <!-- add a space after the user mention -->
7 </template>
8 </span>
9 </div>
10</template>
11
12<script>
13export default {
14 data() {
15 return {
show all 27 lines1import { Component } from '@angular/core';
2
3@Component({
4 selector: 'app-message',
5 template: `
6 <span>
7 <ng-container *ngFor="let messagePart of messageParts">
8 <ng-container *ngIf="messagePart.type==='mention'">
9 <a [href]="getPubnubProfileUrl(messagePart.content.id)">
10 {{ messagePart.content.name }}
11 </a>
12
13 </ng-container>
14 <ng-container *ngIf="messagePart.type!=='mention'">
15 <!-- render other message elements, like text:
show all 33 linesModify display color
Change the mentions display color from the default blue to green.
- React
- React Native
- Vue
- Angular
1const renderMessagePart = (messagePart: MixedTextTypedElement) => {
2 if (messagePart.type === "mention") {
3 const linkStyle = {
4 color: "green", // set the color to green
5 // add any other desired styles here, e.g., textDecoration: "underline"
6 };
7
8 return (
9 <a href={`https://pubnub.com/${messagePart.content.id}`} style={linkStyle}>
10 {messagePart.content.name}
11 </a>
12 );
13 }
14
15 return "";
show all 16 lines1import React from 'react';
2import { Text } from 'react-native';
3
4const renderMessagePart = (messagePart) => {
5 if (messagePart.type === "mention") {
6 const linkStyle = {
7 color: "green", // set the color to green
8 // add any other desired styles here, e.g., textDecorationLine: "underline"
9 };
10
11 return (
12 <Text style={linkStyle}>
13 {messagePart.content.name}
14 </Text>
15 );
show all 19 lines1<template>
2 <div>
3 <span v-for="messagePart in messageParts" :key="messagePart.id">
4 <a v-if="messagePart.type === 'mention'"" :href="`https://pubnub.com/${messagePart.content.id}`" :style="linkStyle">
5 {{ messagePart.content.name }}
6 </a>
7 <!-- render other message elements, like text:
8 <span v-else>
9 <span :style="color: green;" v-if="messagePart.type === 'text'">{{ messagePart.content.text }}</span>
10 </span> -->
11 </span>
12 </div>
13</template>
14
15<script>
show all 31 lines1import { Component } from '@angular/core';
2
3@Component({
4 selector: 'app-message',
5 template: `
6 <ng-container *ngFor="let messagePart of messageParts">
7 <a *ngIf="messagePart.type === 'mention'"
8 [href]="'https://pubnub.com/' + messagePart.content.id"
9 style="color: green;">
10 {{ messagePart.content.name }}
11 </a>
12 </ng-container>
13 `,
14})
15export class MessageComponent {
show all 21 linesShow linked mention preview
getMessagePreview() returns message draft elements (text, user mentions, channel references, URLs). Format each element type separately, such as rendering mentions as profile links.
Method signature
Head to the Links documentation for details on the method signature, input, and output parameters.
Sample code
Show a preview of the linked mention.
1messageDraft.getMessagePreview()
For examples of how you can customize linked mention previews, refer to the getMessageElements() method that's similar in structure but is meant for final, published messages.
Collect all user-related mentions
getCurrentUserMentions() retrieves all instances where the current user was mentioned in channels or threads. Use this to build a mentions feed.
Method signature
This method has the following signature:
1chat.getCurrentUserMentions({
2 startTimetoken?: string;
3 endTimetoken?: string;
4 count?: number;
5}): Promise<{
6 mentions: UserMention[];
7 isMore: boolean;
8}>
Input
| Parameter | Description |
|---|---|
startTimetokenType: stringDefault: n/a | Timetoken delimiting the start of a time slice (exclusive) to pull messages with mentions from. For details, refer to the Fetch History section. |
endTimetokenType: stringDefault: n/a | Timetoken delimiting the end of a time slice (inclusive) to pull messages with mentions from. For details, refer to the Fetch History section. |
countType: numberDefault: 100 | Number of historical messages with mentions to return in a single call. Since each call returns all attached message actions by default, the maximum number of returned messages is 100. For more details, refer to the description of the includeMessageActions parameter in the JavaScript SDK docs. |
Output
| Parameter | Description |
|---|---|
Promise<>Type: object | Returned object containing two fields: mentions and isMore. |
→ mentionsType: UserMention[] | Array listing the requested number of historical mention events with a set of information that differ slightly depending on whether you were mentioned in the main (parent) channel or in a thread. For mentions in the parent channel, the returned ChannelMentionData includes these fields: event (of type mention), channelId where you were mentioned, message that included the mention, userId that mentioned you. For mentions in threads, the returned ThreadMentionData includes similar fields, the only difference is that you'll get parentChannelId and threadChannelId fields instead of just channelId to clearly differentiate the thread that included the mention from the parent channel in which this thread was created. |
→ isMoreType: boolean | Info whether there are more historical events to pull. |
Sample code
List the last ten mentions for the current chat user.
1await chat.getCurrentUserMentions(
2 {
3 count: 10
4 }
5)
Show notifications for mentions
onMentioned() monitors mention events on the User object. Use this to trigger notifications.
Method signature
1user.onMentioned(callback: (mention: Mention) => void): () => void
The Mention object: messageTimetoken (string), channelId (string), parentChannelId (string | undefined), mentionedByUserId (string).
Sample code
1const user = chat.currentUser
2const stopListening = user.onMentioned((mention) => {
3 console.log(`Mentioned in ${mention.channelId} at ${mention.messageTimetoken} by ${mention.mentionedByUserId}`)
4})
Create message with mentions
createMessageDraft() creates a draft message with user mentions.
Mentioned users are added to the MessageDraft object and stored in message metadata when sent.
Method signature
Head over to the Drafts documentation for details on the method signature, input, and output parameters.
Sample code
Create a message mentioning channel members @James, Sarah and @Twain, Mark.
1// version 2
2messageDraft = channel.createMessageDraft({ userSuggestionSource: "global" })
3
4// Add initial text
5messageDraft.update("Hello Alex and Sarah!")
6
7// Add a user mention to the string "Alex"
8messageDraft.addMention(6, 4, "mention", "alex_d"))
9
10// Add a user mention to the string "Alex"
11messageDraft.addMention(15, 5, "mention", "sarah_j"))
12
13// version 1
14const newMessageDraft = this.channel.createMessageDraft({ userSuggestionSource: "channel" })
15const suggestedUsers = []
show all 27 linesTrack mentions
Use the Message draft state listener to track mentions.
onChange() detects @ mentions in text input. When found, return suggested users and add them to the mention.
Method signature
This method has the following signature:
1messageDraft.onChange(text: string): Promise<{
2 users: {
3 nameOccurrenceIndex: number;
4 suggestedUsers: User[];
5 };
6 channels: {
7 channelOccurrenceIndex: number;
8 suggestedChannels: Channel[];
9 };
10}>
Input
| Parameter | Description |
|---|---|
text *Type: stringDefault: n/a | Typed in a message containing @ that is mapped to a specific user's name (or # for a channel reference). |
Output
| Parameter | Description |
|---|---|
Promise<>Type: object | Returned object containing these fields: users (for @mentions) and channels (for #references). |
usersType: object | Returned object containing these fields for mentioned users: nameOccurrenceIndex and suggestedUsers. |
→ nameOccurrenceIndexType: number | Specific occurrence of @ in the message (like 3) that is mapped to a given user. |
→ suggestedUsersType: User[] | List of users that match the typed text after @, like Mark for @Mar. |
channelsType: object | Returned object containing these fields for referenced channels: channelOccurrenceIndex and suggestedChannels. |
→ channelOccurrenceIndexType: number | Specific occurrence of # in the message (like 3) that is mapped to a given channel. |
→ suggestedChannelsType: Channel[] | List of channels that match the typed text after #, like Support for #Sup. |
Sample code
Track mentions for messages on the current channel.
1const newMessageDraft = this.channel?.createMessageDraft()
2
3 async handleInput(text: string) {
4 const response = await newMessageDraft.onChange(text)
5
6 const suggestedUsers = response.users.suggestedUsers
7 const lastAffectedNameOccurrenceIndex = response.users.nameOccurrenceIndex
8 }
Get user suggestions
For user suggestions, use MessageDraft.addChangeListener().
Add mentioned user
For adding mentioned users, use MessageDraft.addMention().