---
source_url: https://www.pubnub.com/docs/chat/chat-sdk/build/features/users/mentions
title: Mention users
updated_at: 2026-06-01T12:01:24.734Z
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Mention users

Tag users in chat messages with `@` mentions. Type `@` followed by at least three letters to see username suggestions.

:::tip 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](https://www.pubnub.com/docs/sdks/javascript/api-reference/objects#set-user-metadata)
* **Mentions per message**: up to 100 (default: 10)

Implementation follows similar patterns to [channel referencing](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/references) and [links](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/links).

:::note Requires App Context
Enable [App Context](https://youtu.be/9UEoSlngpYI) in the [Admin Portal](https://admin.pubnub.com/) to mention users.
:::

## Interactive demo

See user mentions and [channel references](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/references) in action with this React demo.

:::tip Want to implement something similar?
[Implementation guide](https://www.pubnub.com/how-to/chat-sdk-mention-users/) | [Source code](https://github.com/PubNubDevelopers/Chat-SDK-How-Tos/tree/main/mentions)
:::

### 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](https://www.pubnub.com/docs/chat/chat-sdk/learn/chat-entities/message-draft). 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()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/drafts#add-message-element) 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.

```ts
// Create a message draft
messageDraft = channel.createMessageDraft({ userSuggestionSource: "global" })

// Add initial text
messageDraft.update("Hello Alex!")

// Add a user mention to the string "Alex"
messageDraft.addMention(6, 4, "mention", "alex_d")
```

## Remove user mentions

`removeMention()` removes a user mention from a [draft message](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/drafts).

### 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()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/drafts#remove-message-element) method for details.

:::warning 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.

```ts
// assume the message reads
// Hello Alex! I have sent you this link on the #offtopic channel.`

// remove the channel reference
messageDraft.removeMention(6)
```

## Send message with mentions

`send()` publishes the text message with mentioned users and emits [events of type mention](https://www.pubnub.com/docs/chat/chat-sdk/build/features/custom-events#events-for-mentions).

##### Under the hood

`send()` calls Pub/Sub API and the JavaScript SDK [publish()](https://www.pubnub.com/docs/sdks/javascript/api-reference/publish-and-subscribe#publish) method.

### Method signature

Head over to the [Drafts](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/drafts#send-a-draft-message) 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`.

```ts
// Create a new MessageDraft instance with the suggested user source as "channel"
const messageDraft = channel.createMessageDraft({
  userSuggestionSource: "channel"
});

// Change the text
messageDraft.update("Hello @James, Sara and @Twain, Mark.")

// Add first user mention
messageDraft.addMention(7, 12, "mention", "sarah_j")

// Add second user mention
messageDraft.addMention(24, 12, "mention", "twain_m")

messageDraft.send().then((response) => {
  console.log('Message sent successfully', response);
}).catch((error) => {
  console.error('Error sending message', error);
});
```

## Show 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](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/links#render-urls) and [channel references](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/references#show-referenced-channel-as-link).

### Method signature

Head over to the [Links](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/links#render-urls) documentation for details on the method signature, input, and output parameters.

### Sample code

Show all linked mentions in a message as clickable links.

```ts
message.getMessageElements()
```

### Other examples

Customize mention rendering with these examples.

#### Add company links

Add a link to a PubNub profile under each user mention.

##### React

```ts
const renderMessagePart = (messagePart: MixedTextTypedElement) => {
  if (messagePart.type === "mention") {
    // assuming messagePart.content.id is the user ID
    const pubnubProfileUrl = `https://pubnub.com/profiles/${messagePart.content.id}`;
    return (
      <span>
        <a href={pubnubProfileUrl}>{messagePart.content.name}</a>
        {" "}
        {/* add a space after the user mention */}
      </span>
    );
  }
  return "";
}
```

##### React Native

```jsx
import React from 'react';
import { Text, Linking, View } from 'react-native';

const renderMessagePart = (messagePart) => {
  if (messagePart.type === "mention") {
    const pubnubProfileUrl = `https://pubnub.com/profiles/${messagePart.content.id}`;
    return (
      <View>
        <Text>
          <Text onPress={() => Linking.openURL(pubnubProfileUrl)}>
            {messagePart.content.name}
          </Text>
          {" "}
        </Text>
      </View>
    );
  }
  return null;
}
```

##### Vue

```ts
<template>
  <div>
    <span v-for="messagePart in messageParts" :key="messagePart.content.id">
      <template v-if="messagePart.type === 'mention'">
        <a :href="getPubnubProfileUrl(messagePart.content.id)">{{ messagePart.content.name }}</a>
        &nbsp; <!-- add a space after the user mention -->
      </template>
    </span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      messageParts: [
        // array of message parts
      ]
    };
  },
  methods: {
    getPubnubProfileUrl(userId) {
      return `https://pubnub.com/profiles/${userId}`;
    },
  },
};
</script>
```

##### Angular

```ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-message',
  template: `
    <span>
      <ng-container *ngFor="let messagePart of messageParts">
        <ng-container *ngIf="messagePart.type==='mention'">
          <a [href]="getPubnubProfileUrl(messagePart.content.id)">
            {{ messagePart.content.name }}
          </a>
          &nbsp;
        </ng-container>
        <ng-container *ngIf="messagePart.type!=='mention'">
        <!-- render other message elements, like text:
        <ng-container *ngIf="messagePart.type === 'text'>
          <span style="color:green;">{{messagePart.content.text}}</span>
        </ng-container>"-->
        </ng-container>
      </ng-container>
    </span>
  `
})
export class MessageComponent {
  messageParts: MixedTextTypedElement[] = [
    // assuming you have an array of message parts
  ];

  getPubnubProfileUrl(id: string): string {
    // assuming you have a function to generate the PubNub profile URL
    return `https://pubnub.com/profiles/${id}`;
  }
}
```

#### Modify display color

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

##### React

```ts
const renderMessagePart = (messagePart: MixedTextTypedElement) => {
  if (messagePart.type === "mention") {
    const linkStyle = {
      color: "green", // set the color to green
      // add any other desired styles here, e.g., textDecoration: "underline"
    };

    return (
      <a href={`https://pubnub.com/${messagePart.content.id}`} style={linkStyle}>
        {messagePart.content.name}
      </a>
    );
  }

  return "";
}
```

##### React Native

```tsx
import React from 'react';
import { Text } from 'react-native';

const renderMessagePart = (messagePart) => {
  if (messagePart.type === "mention") {
    const linkStyle = {
      color: "green", // set the color to green
      // add any other desired styles here, e.g., textDecorationLine: "underline"
    };

    return (
      <Text style={linkStyle}>
        {messagePart.content.name}
      </Text>
    );
  }

  return null;
}
```

##### Vue

```html
<template>
  <div>
    <span v-for="messagePart in messageParts" :key="messagePart.id">
      <a v-if="messagePart.type === 'mention'"" :href="`https://pubnub.com/${messagePart.content.id}`" :style="linkStyle">
        {{ messagePart.content.name }}
      </a>
      <!-- render other message elements, like text:
      <span v-else>
        <span :style="color: green;" v-if="messagePart.type === 'text'">{{ messagePart.content.text }}</span>
      </span> -->
    </span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      messageParts: [
        { type: "text", content: "Hello" },
        { type: "mention", content: { id: 1, name: "John Doe" } },
        { type: "text", content: "!" },
      ],
      linkStyle: {
        color: "green", // set the color to green
        // add any other desired styles here, e.g., textDecoration: "underline"
      },
    };
  },
};
</script>
```

##### Angular

```ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-message',
  template: `
    <ng-container *ngFor="let messagePart of messageParts">
      <a *ngIf="messagePart.type === 'mention'"
         [href]="'https://pubnub.com/' + messagePart.content.id"
         style="color: green;">
        {{ messagePart.content.name }}
      </a>
    </ng-container>
  `,
})
export class MessageComponent {
  messageParts: MixedTextTypedElement[];

  constructor() {
    // initialize messageParts here
  }
}
```

## Show linked mention preview

`getMessagePreview()` returns message draft elements (text, user mentions, [channel references](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/references), [URLs](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/links)). Format each element type separately, such as rendering mentions as profile links.

### Method signature

Head to the [Links](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/links#show-text-link-preview) documentation for details on the method signature, input, and output parameters.

### Sample code

Show a preview of the linked mention.

```ts
messageDraft.getMessagePreview()
```

For examples of how you can customize linked mention previews, refer to the [getMessageElements() method](https://www.pubnub.com/docs/chat/chat-sdk/build/features/users/mentions#show-mention-as-link) 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.

##### Under the hood

`getCurrentUserMentions()` calls Message Persistence API and the JavaScript SDK [fetchMessages()](https://www.pubnub.com/docs/sdks/javascript/api-reference/storage-and-playback#fetch-history) method.

### Method signature

This method has the following signature:

```ts
chat.getCurrentUserMentions({
    startTimetoken?: string;
    endTimetoken?: string;
    count?: number;
}): Promise<{
    mentions: UserMention[];
    isMore: boolean;
}>
```

#### Input

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| startTimetoken | string | Optional |  | [Timetoken](https://www.pubnub.com/docs/sdks/javascript/api-reference/misc#time) delimiting the start of a time slice (exclusive) to pull messages with mentions from. For details, refer to the [Fetch History section](https://www.pubnub.com/docs/sdks/javascript/api-reference/storage-and-playback#fetch-history). |
| endTimetoken | string | Optional |  | Timetoken delimiting the end of a time slice (inclusive) to pull messages with mentions from. For details, refer to the [Fetch History section](https://www.pubnub.com/docs/sdks/javascript/api-reference/storage-and-playback#fetch-history). |
| count | number | Optional | `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](https://www.pubnub.com/docs/sdks/javascript/api-reference/storage-and-playback#methods). |

#### Output

| Parameter | Description |
| --- | --- |
| `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](https://www.pubnub.com/docs/general/setup/users-and-devices) 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.

```ts
await chat.getCurrentUserMentions(
    {
        count: 10
    }
)
```

## Show notifications for mentions

`onMentioned()` monitors mention events on the `User` object. Use this to trigger notifications.

### Method signature

```ts
user.onMentioned(callback: (mention: Mention) => void): () => void
```

The `Mention` object: `messageTimetoken` (string), `channelId` (string), `parentChannelId` (string | undefined), `mentionedByUserId` (string).

### Sample code

```ts
const user = chat.currentUser
const stopListening = user.onMentioned((mention) => {
    console.log(`Mentioned in ${mention.channelId} at ${mention.messageTimetoken} by ${mention.mentionedByUserId}`)
})
```

## Create message with mentions

`createMessageDraft()` creates a draft message with user mentions.

Mentioned users are added to the [MessageDraft object](https://www.pubnub.com/docs/chat/chat-sdk/learn/chat-entities/message-draft) and stored in message metadata when sent.

### Method signature

Head over to the [Drafts](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/drafts#create-a-draft-message) documentation for details on the method signature, input, and output parameters.

### Sample code

Create a message mentioning channel members `@James, Sarah` and `@Twain, Mark`.

```ts
// version 2
messageDraft = channel.createMessageDraft({ userSuggestionSource: "global" })

// Add initial text
messageDraft.update("Hello Alex and Sarah!")

// Add a user mention to the string "Alex"
messageDraft.addMention(6, 4, "mention", "alex_d"))

// Add a user mention to the string "Alex"
messageDraft.addMention(15, 5, "mention", "sarah_j"))

// version 1
const newMessageDraft = this.channel.createMessageDraft({ userSuggestionSource: "channel" })
const suggestedUsers = []
const lastAffectedNameOccurrenceIndex = -1

async handleInput(text: string) {
const response = await newMessageDraft.onChange(text)
suggestedUsers = response.users.suggestedUsers
lastAffectedNameOccurrenceIndex = response.users.nameOccurrenceIndex
}

handleInput("Hello @James, Sarah")
newMessageDraft.addMentionedUser(suggestedUsers[0], lastAffectedNameOccurrenceIndex)
handleInput("@Twain, Mark")
newMessageDraft.addMentionedUser(suggestedUsers[0], lastAffectedNameOccurrenceIndex)
```

## Track mentions

Use the [Message draft state](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/drafts#add-message-draft-change-listener) listener to track mentions.

`onChange()` detects `@` mentions in text input. When found, [return suggested users](#get-user-suggestions) and [add them](#add-mentioned-user) to the mention.

##### Under the hood

`onChange()` calls PubNub App Context API and the JavaScript SDK [getChannelMembers()](https://www.pubnub.com/docs/sdks/javascript/api-reference/objects#channel-members) method (for the `channel` user suggestion source) and the [getAllUUIDMetadata()](https://www.pubnub.com/docs/sdks/javascript/api-reference/objects#get-user-metadata) method (for the `global` user suggestion source).

### Method signature

This method has the following signature:

```ts
messageDraft.onChange(text: string): Promise<{
    users: {
        nameOccurrenceIndex: number;
        suggestedUsers: User[];
    };
    channels: {
        channelOccurrenceIndex: number;
        suggestedChannels: Channel[];
    };
}>
```

#### Input

| Parameter | Description |
| --- | --- |
| `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](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/references)). |

#### Output

| Parameter | Description |
| --- | --- |
| `Promise<>`Type: `object` | Returned object containing these fields: `users` (for @mentions) and `channels` (for [#references](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/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.

```ts
const newMessageDraft = this.channel?.createMessageDraft()

  async handleInput(text: string) {
    const response = await newMessageDraft.onChange(text)

    const suggestedUsers = response.users.suggestedUsers
    const lastAffectedNameOccurrenceIndex = response.users.nameOccurrenceIndex
  }
```

## Get user suggestions

For user suggestions, use [MessageDraft.addChangeListener()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/drafts#add-message-draft-change-listener).

## Add mentioned user

For adding mentioned users, use [MessageDraft.addMention()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/drafts#add-message-element).

## Remove mentioned user

Use [MessageDraft.removeMention()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/drafts#remove-message-element).