Support reactions in your app built with XMTP
Use the reaction content type to support reactions in your app. A reaction is a quick and often emoji-based way to respond to a message. Reactions are usually limited to a predefined set of emojis or symbols provided by the chat app.
Use a local database for performance
Use a local database to store reactions. This enables your app to performantly display a reaction with its referenced message when rendering message lists.
Configure the content type
For Browser SDK (v6.0.0+) and Node SDK (v5.0.0+), reactions are built-in and do not require codec registration. Skip this step for these SDKs.
For other SDKs, register the codec:
const client = await Client.create(signer, {
env: 'production',
codecs: [new ReactionCodec()],
});Send a reaction
With XMTP, reactions are represented as objects with the following keys:
-
reference: ID of the message being reacted to -
referenceInboxId: (Optional) Inbox ID of the sender of the message being reacted to. This helps with message attribution in group conversations. -
action: Action of the reaction (added or removed) -
content: String representation of the reaction (smile, for example) to be interpreted by clients -
schema: Schema of the reaction (Unicode, shortcode, or custom)
import { ReactionAction, ReactionSchema } from '@xmtp/browser-sdk';
const reaction = {
reference: someMessageID,
referenceInboxId: messageSenderInboxId, // Optional: Inbox ID of the message sender
action: ReactionAction.Added,
content: 'smile',
schema: ReactionSchema.Shortcode,
};
await conversation.sendReaction(reaction);Receive a reaction
Now that you can send a reaction, you need a way to receive reactions. For Browser SDK and Node SDK, reactions are accessed via the reactions property on a message, which returns an array of DecodedMessage<Reaction> objects.
import { ReactionAction, ReactionSchema } from '@xmtp/browser-sdk';
const messages = await conversation.messages();
const message = messages[0];
// Access reactions on the message
const reactions = message.reactions;
for (const reactionMessage of reactions) {
const reaction = reactionMessage.content;
console.log(reaction.content); // e.g., "👍"
console.log(reaction.action); // ReactionAction.Added or ReactionAction.Removed
console.log(reaction.schema); // ReactionSchema.Unicode, ReactionSchema.Shortcode, or ReactionSchema.Custom
}
