How to Add Reactions and Emoji to Messages with the PubNub Chat SDK
Tags: chatsdk, typescriptsdk, chatjavascript
Published: 2023-12-20 08:12:50

Introduction to the PubNub Chat SDK
-----------------------------------

The PubNub Chat SDK, available for TypeScript and JavaScript applications, exposes a set of APIs designed to make it easy to add powerful and flexible chat features to your app with minimum development. Chat options like [quoting](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/quotes), [mentioning users](https://www.pubnub.com/docs/chat/chat-sdk/build/features/users/mentions), [channel references](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/references), [threads](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/threads), [read receipts](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/read-receipts), and [typing indicators](https://www.pubnub.com/docs/chat/chat-sdk/build/features/typing-indicator) are supported natively by the SDK, letting you build a full-fledged app quickly.

Please refer to our [documentation](https://www.pubnub.com/docs/chat/chat-sdk/overview) and [sample chat app](https://www.pubnub.com/docs/chat/chat-sdk/build/sample-chat) to get started with the Chat SDK. Our [tutorial](https://www.pubnub.com/tutorials/chat-sdk/) will walk you through the basic functionality of the Chat SDK and touch on some more advanced features whilst our [hosted demo](https://www.pubnub.com/demos/chat-sdk-mobile/) will show the Chat SDK in action.

This how-to is part of a **series of posts** diving into some of the more powerful features of the PubNub Chat SDK. The series can be read in any order, but the list of related articles is below:

-   [How to Manage User Channel Membership with the Chat SDK](https://pubnub.com/how-to/chat-sdk-manage-user-channel-membership/)
-   [How to Add Reactions and Emojis to Messages with the Chat SDK](https://pubnub.com/how-to/chat-sdk-add-reactions-to-messages/)
-   [How to Create Threads and Quote Messages with the Chat SDK](https://pubnub.com/how-to/chat-sdk-create-threads-and-quote-messges/)
-   [How to Mention Users and Channels with the Chat SDK](https://pubnub.com/how-to/chat-sdk-mention-users/)

Add Reactions and Emojis to Messages
------------------------------------

Being able to react to a message is a fundamental part of many chat implementations, for example, giving a message a thumbs up or a smiley face emoji. You might see the terminology ‘message reactions’ and ‘emoji’ used interchangeably, but understand that they are describing the same thing - this is **not sending** an emoji as part of the message.

### Prerequisites

Ensure you have an instance of the [Chat object](https://www.pubnub.com/docs/chat/chat-sdk/learn/chat-entities/chat) instantiated in your app

```js
const chat = await Chat.init({
  publishKey: "YOUR_PUBLISH_KEY",
  subscribeKey: "YOUR_SUBSCRIBE_KEY",
  userId: "YOUR_USER_ID",
})
```

There are a lot of possible parameters you can pass to the Chat SDK, but for message reactions, you do not need anything more than the standard publish key, subscribe key, and user ID. If all of this is new to you, and you’re not sure where to get started, please check out the [initial configuration](https://www.pubnub.com/docs/chat/chat-sdk/build/configuration) section in our documentation.

### Message Reactions

To express a reaction to a message, call the [message.toggleReaction()](https://pubnub.com/docs/chat/chat-sdk/build/features/messages/emojis#add--delete) API.

```js
// add the "thumb up" emoji to that message
const newMsg = await message.toggleReaction("👍")
```

[Message](https://pubnub.com/docs/chat/chat-sdk/learn/chat-entities/message) is a fundamental type within the Chat SDK, and you are most likely rendering your messages within a list, but how the user chooses a reaction will depend on your UX.

There are no setReaction(...) or deleteReaction(...) methods; the only way to apply or remove a reaction to a message is to use the [toggleReaction()](https://pubnub.com/docs/chat/chat-sdk/build/features/messages/emojis#add--delete) API. ToggleReaction() will return a new copy of the message, which should replace the existing messages in the user’s list.

To retrieve reactions, the Chat SDK can either notify you via callback, or you can query a specific message to ask what reactions it has applied.

### Querying a message’s reactions

To query the reactions applied to a single message, use the [message.reactions](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/reactions#get-reactions-for-one-message) API:

```js
message.reactions["👍"]
```

Remember, a message can have multiple emoji reactions (🙂🥰🥳), and multiple users might have applied each emoji. The return value from ‘message.reactions’ therefore, is a JSON Object, with each key being a different emoji. The value associated with each key is an array containing all the user IDs who applied the emoji, along with the time the reaction was applied.

```js
{
  "🥳": [
      {
        "uuid": "user-1",
        "actionTimetoken": "16983289196082900"
      }
    ],
  "🙂": [
      {
        "uuid": "user-1",
        "actionTimetoken": "16983290238341020"
      },
      {
        "uuid": "user-2",
        "actionTimetoken": "16983290238341020"
      }
    ]
}
```

### Receiving notifications when a message’s reactions update

To be notified when a message’s reactions change, the Chat SDK exposes the [streamUpdates() and streamUpdatesOn()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/updates#get-message-updates) methods. StreamUpdates() can be invoked on a single message object to register a callback invoked when only that message’s reactions change. Still, it is more common that you want to be notified when any message in a conversation or thread receives a reaction, and for this more prolific use case, you should use streamUpdatesOn().

StreamUpdatesOn() is a static method of the [Message](https://www.pubnub.com/docs/chat/chat-sdk/learn/chat-entities/message) class, also inherited in the [ThreadMessage](https://www.pubnub.com/docs/chat/chat-sdk/learn/chat-entities/thread-message) class. It is common to have a conversation in a single channel displayed in one view, but if you expand a message thread, that thread is displayed in a separate view. In this example, you might use Message.streamUpdatesOn() for the main view and ThreadMessage.streamUpdatesOn() for the thread view.

```js
Message.streamUpdatesOn(messages, (messages) => {
  console.log("Updated messages: ", messages)
})
```

The value returned in the streamUpdates()/streamUpdatesOn() callback is the updated message/messages instance, so be sure to update your application’s UI accordingly.

### Putting it all together

One possible implementation would be to store the current conversation messages in the application state, which is updated with streamMessages(). The current messages displayed to the user are rendered from that application state and as part of that render function, [message.reactions](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/reactions#get-reactions-for-one-message) will determine which emoji should be displayed next to each message. If the user interacts with the message to add a reaction to it, use [toggleReaction](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/reactions#add--delete) to notify the Chat SDK and update the application state

You can see this behavior in the short demo below. This is a real, live, working demo, so feel free to launch the demo in multiple tabs to see real-time reactions shared between participants:

Interactive Demo
----------------

  
**If the embedded content is not available** on this page, it can also be viewed at [https://chat-sdk-how-to-reactions.netlify.app/](https://chat-sdk-how-to-reactions.netlify.app/)

The code that drives this demo is available on [GitHub](https://github.com/PubNubDevelopers/Chat-SDK-How-Tos/tree/main/reactions), but the key points are:

Click handler when a user left or right clicks a message:

```js
async function handleClick(message: Message, reaction: string)
{
  await message.toggleReaction(reaction)
}
```

When we receive a callback that messages have changed, update our UX

```js
useEffect(() => {
  if (!messages.length) return
    return Message.streamUpdatesOn(messages, setMessages)
}, [messages])
```

Display the reaction against the message. Note that the deliberately simple implementation in this shared demo is effectively a shared reaction where any user can add or remove it. Your implementation will likely display a number next to each emoji to indicate how many people have reacted.:

```js
{message.reactions["🙂"] && message.reactions["🙂"].length !== 0 ? "🙂":""}
{message.reactions["🥳"] && message.reactions["🥳"].length !== 0 ? "🥳":""}
```

### Historical reactions

If you have persistence enabled on your PubNub keyset, messages will be stored by PubNub and can be retrieved through the [Message History](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/history).

The Chat SDK will automatically persist message reactions in history for you, allowing you to access historical reactions without any additional steps. If you previously used our traditional PubNub SDKs, you might be aware that to retrieve historical message reactions, you needed to specify ‘includeMessageActions’ when making the call, but the Chat SDK makes things simpler.

This is illustrated with the following code sample taken [directly from the documentation](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/reactions#basic-usage-1)

```js
// reference the "support" channel with the message you want to check
const channel = await chat.getChannel("support")

// reference the last message on that "support" channel
const message = await channel.getHistory({count: 1}).messages[0]

// list all thumbs-up reactions to the message
console.log(message.reactions["👍"])
```

Demo: Add Reactions with our React Native demo on Mobile
--------------------------------------------------------

You can play with this feature using our Chat SDK Demo for Mobile, available as a [hosted demo](https://www.pubnub.com/demos/chat-sdk-mobile/) with full source code available on [GitHub](https://github.com/pubnub/js-chat/tree/master/samples/react-native-group-chat). **You should also see the demo rendered in an iFrame at the bottom of this section**.

![Two smartphones with messaging app interface showing a conversation between users test-user-917 and test-user-322.](https://images.ctfassets.net/3prze68gbwl1/BaJuGMntJAVtNc2kUNO2t/bfa86180be1bb4e73ef10d81158466f0/reactions-demo.png)

Follow these steps to use message reactions in our demo:

1.  Log in to the application, choosing a random user id for each of the two devices.
2.  Start a conversation from the second device, selecting the user logged into the first device.
3.  Add some messages to the conversation.
4.  Long press on one of the messages.
5.  Select an emoji to react.
6.  Repeat to add a few other emoji
7.  Notice that if you back out of the conversation or even log out of and back into the app, the reactions are retained and read from the message history.

  
**If the embedded content is not available** on this page, it can also be viewed at [https://pubnubdevelopers.github.io/Chat-SDK-Demo/mobile/](https://pubnubdevelopers.github.io/Chat-SDK-Demo/mobile/)

How can PubNub help you?
========================

This article was originally published on [PubNub.com](https://pubnub.com/how-to/chat-sdk-add-reactions-to-messages/)

Our platform helps developers build, deliver, and manage real-time interactivity for web apps, mobile apps, and IoT devices.

The foundation of our platform is the industry's largest and most scalable real-time edge messaging network. With over 15 points-of-presence worldwide supporting 800 million monthly active users, and 99.999% reliability, you'll never have to worry about outages, concurrency limits, or any latency issues caused by traffic spikes.

Experience PubNub
-----------------

Check out [Live Tour](https://www.pubnub.com/tour/introduction/) to understand the essential concepts behind every PubNub-powered app in less than 5 minutes

Get Setup
---------

Sign up for a [PubNub account](https://admin.pubnub.com/signup/) for immediate access to PubNub keys for free

Get Started
-----------

The [PubNub docs](https://www.pubnub.com/docs) will get you up and running, regardless of your use case or [SDK](https://www.pubnub.com/docs)