On this page

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.

icon

Under the hood

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 lines

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 a link to a PubNub profile under each user mention.

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}

Modify display color

Change the mentions display color from the default blue to green.

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 lines

Show 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.

getCurrentUserMentions() retrieves all instances where the current user was mentioned in channels or threads. Use this to build a mentions feed.

icon

Under the hood

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

* required
ParameterDescription
startTimetoken
Type: string
Default:
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.
endTimetoken
Type: string
Default:
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.
count
Type: number
Default:
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

ParameterDescription
Promise<>
Type: object
Returned object containing two fields: mentions and isMore.
 → mentions
Type: 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.
 → isMore
Type: 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 lines

Track 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.

icon

Under the hood

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

* required
ParameterDescription
text *
Type: string
Default:
n/a
Typed in a message containing @ that is mapped to a specific user's name (or # for a channel reference).

Output

ParameterDescription
Promise<>
Type: object
Returned object containing these fields: users (for @mentions) and channels (for #references).
users
Type: object
Returned object containing these fields for mentioned users: nameOccurrenceIndex and suggestedUsers.
 → nameOccurrenceIndex
Type: number
Specific occurrence of @ in the message (like 3) that is mapped to a given user.
 → suggestedUsers
Type: User[]
List of users that match the typed text after @, like Mark for @Mar.
channels
Type: object
Returned object containing these fields for referenced channels: channelOccurrenceIndex and suggestedChannels.
 → channelOccurrenceIndex
Type: number
Specific occurrence of # in the message (like 3) that is mapped to a given channel.
 → suggestedChannels
Type: 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().

Remove mentioned user

Use MessageDraft.removeMention().

Last updated on