DEV Community

Cover image for How to Add Reactions and Emoji to Messages with the PubNub Chat SDK
PubNub Developer Relations for PubNub

Posted on

How to Add Reactions and Emoji to Messages with the PubNub Chat SDK

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, mentioning users, channel references, threads, read receipts, and typing indicators are supported natively by the SDK, letting you build a full-fledged app quickly.

Please refer to our documentation and sample chat app to get started with the Chat SDK. Our tutorial will walk you through the basic functionality of the Chat SDK and touch on some more advanced features whilst our hosted demo 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:

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 instantiated in your app

const chat = await Chat.init({
  publishKey: "YOUR_PUBLISH_KEY",
  subscribeKey: "YOUR_SUBSCRIBE_KEY",
  userId: "YOUR_USER_ID",
})
Enter fullscreen mode Exit fullscreen mode

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 section in our documentation.

Message Reactions

To express a reaction to a message, call the message.toggleReaction() API.

// add the "thumb up" emoji to that message
const newMsg = await message.toggleReaction("👍")
Enter fullscreen mode Exit fullscreen mode

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() 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 API:

message.reactions["👍"]
Enter fullscreen mode Exit fullscreen mode

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.

{
  "🥳": [
      {
        "uuid": "user-1",
        "actionTimetoken": "16983289196082900"
      }
    ],
  "🙂": [
      {
        "uuid": "user-1",
        "actionTimetoken": "16983290238341020"
      },
      {
        "uuid": "user-2",
        "actionTimetoken": "16983290238341020"
      }
    ]
}
Enter fullscreen mode Exit fullscreen mode

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() 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 class, also inherited in the ThreadMessage 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.

Message.streamUpdatesOn(messages, (messages) => {
  console.log("Updated messages: ", messages)
})
Enter fullscreen mode Exit fullscreen mode

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 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 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/

The code that drives this demo is available on GitHub, but the key points are:

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

async function handleClick(message: Message, reaction: string)
{
  await message.toggleReaction(reaction)
}
Enter fullscreen mode Exit fullscreen mode

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

useEffect(() => {
  if (!messages.length) return
    return Message.streamUpdatesOn(messages, setMessages)
}, [messages])
Enter fullscreen mode Exit fullscreen mode

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

{message.reactions["🙂"] && message.reactions["🙂"].length !== 0 ? "🙂":""}
{message.reactions["🥳"] && message.reactions["🥳"].length !== 0 ? "🥳":""}
Enter fullscreen mode Exit fullscreen mode

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.

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

// 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["👍"])
Enter fullscreen mode Exit fullscreen mode

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 with full source code available on GitHub. 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.

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/

How can PubNub help you?

This article was originally published on PubNub.com

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 to understand the essential concepts behind every PubNub-powered app in less than 5 minutes

Get Setup

Sign up for a PubNub account for immediate access to PubNub keys for free

Get Started

The PubNub docs will get you up and running, regardless of your use case or SDK

Top comments (0)