Skip to main content
FieldValue
Package@cometchat/chat-uikit-react
Importimport { CometChatLocalize } from "@cometchat/chat-uikit-react";
Set LanguageCometChatLocalize.setCurrentLanguage("fr")
Add TranslationsCometChatLocalize.addTranslation({ "en-US": { "key": "value" } })
Supported Languages19 languages including en-US, fr, de, es, ja, zh, and more
Date FormattingUse CalendarObject for custom date/time patterns

Overview

This guide shows you how to add multi-language support to your CometChat React app. You’ll learn to set languages, add custom translations, and format dates for different locales. Time estimate: 10 minutes Difficulty: Beginner

Prerequisites

Use Cases

Localization is essential for:
  • Global apps — Support users in their native language
  • Regional compliance — Display dates/times in local formats
  • Custom terminology — Replace default UI text with your brand’s language
  • Accessibility — Improve comprehension for non-English speakers

Supported Languages

LanguageCodeLanguageCode
English (US)en-USJapaneseja
English (UK)en-GBKoreanko
FrenchfrPortuguesept
GermandeRussianru
SpanishesChinesezh
ItalianitChinese (Traditional)zh-TW
DutchnlMalayms
HindihiSwedishsv
TurkishtrLithuanianlt
Hungarianhu

Steps

Step 1: Initialize Localization

Configure localization during app initialization:
App.tsx
import { useEffect } from "react";
import { CometChatUIKit, UIKitSettingsBuilder } from "@cometchat/chat-uikit-react";
import { CometChatLocalize } from "@cometchat/chat-uikit-react";

function App() {
  useEffect(() => {
    const UIKitSettings = new UIKitSettingsBuilder()
      .setAppId("APP_ID")
      .setRegion("REGION")
      .setAuthKey("AUTH_KEY")
      .build();

    CometChatUIKit.init(UIKitSettings).then(() => {
      // Initialize localization after UI Kit init
      CometChatLocalize.init({
        language: "es",
        fallbackLanguage: "en-US",
        disableAutoDetection: false,
      });

      CometChatUIKit.login("UID");
    });
  }, []);

  return <div>{/* Your chat components */}</div>;
}

export default App;

Step 2: Set Language at Runtime

Change the language dynamically without reloading:
LanguageSwitcher.tsx
import { CometChatLocalize } from "@cometchat/chat-uikit-react";

function LanguageSwitcher() {
  const languages = [
    { code: "en-US", label: "English" },
    { code: "es", label: "Español" },
    { code: "fr", label: "Français" },
    { code: "de", label: "Deutsch" },
    { code: "ja", label: "日本語" },
  ];

  const handleLanguageChange = (langCode: string) => {
    CometChatLocalize.setCurrentLanguage(langCode);
  };

  return (
    <select
      onChange={(e) => handleLanguageChange(e.target.value)}
      defaultValue={CometChatLocalize.getCurrentLanguage()}
    >
      {languages.map((lang) => (
        <option key={lang.code} value={lang.code}>
          {lang.label}
        </option>
      ))}
    </select>
  );
}

export default LanguageSwitcher;

Step 3: Add Custom Translations

Add or override translations for specific keys:
CustomTranslations.tsx
import { useEffect } from "react";
import { CometChatLocalize } from "@cometchat/chat-uikit-react";

function useCustomTranslations() {
  useEffect(() => {
    CometChatLocalize.addTranslation({
      "en-US": {
        "welcome_message": "Welcome to Support Chat!",
        "send_message": "Send",
        "type_message": "Type your message...",
      },
      "es": {
        "welcome_message": "¡Bienvenido al Chat de Soporte!",
        "send_message": "Enviar",
        "type_message": "Escribe tu mensaje...",
      },
      "fr": {
        "welcome_message": "Bienvenue sur le Chat Support!",
        "send_message": "Envoyer",
        "type_message": "Tapez votre message...",
      },
    });
  }, []);
}

export default useCustomTranslations;

Step 4: Customize Date/Time Formatting

Use CalendarObject to customize how dates and times are displayed:
DateFormatting.tsx
import { CometChatLocalize, CalendarObject } from "@cometchat/chat-uikit-react";

// Global date format configuration
CometChatLocalize.init({
  language: "en-US",
  timezone: "America/New_York",
  calendarObject: new CalendarObject({
    today: "[Today at] hh:mm A",
    yesterday: "[Yesterday at] hh:mm A",
    lastWeek: "dddd [at] hh:mm A",
    otherDays: "MMM DD, YYYY [at] hh:mm A",
    relativeTime: {
      minute: "%d minute ago",
      minutes: "%d minutes ago",
      hour: "%d hour ago",
      hours: "%d hours ago",
    },
  }),
});
For Spanish locale:
CometChatLocalize.init({
  language: "es",
  timezone: "Europe/Madrid",
  calendarObject: new CalendarObject({
    today: "[Hoy a las] HH:mm",
    yesterday: "[Ayer a las] HH:mm",
    lastWeek: "[El] dddd [a las] HH:mm",
    otherDays: "DD MMM YYYY, HH:mm",
    relativeTime: {
      minute: "hace %d minuto",
      minutes: "hace %d minutos",
      hour: "hace %d hora",
      hours: "hace %d horas",
    },
  }),
});

Step 5: Component-Specific Date Formats

Override date formats for specific components:
MessageHeaderWithCustomDate.tsx
import { CometChatMessageHeader, CalendarObject } from "@cometchat/chat-uikit-react";
import { CometChat } from "@cometchat/chat-sdk-javascript";

function MessageHeaderWithCustomDate({ user }: { user: CometChat.User }) {
  return (
    <CometChatMessageHeader
      user={user}
      lastActiveAtDateTimeFormat={
        new CalendarObject({
          today: "[Active today at] hh:mm A",
          yesterday: "[Active yesterday]",
          lastWeek: "[Active] dddd",
          otherDays: "[Active] MMM DD",
        })
      }
    />
  );
}

export default MessageHeaderWithCustomDate;

Complete Example

Here’s a full implementation with language switching and custom translations:
LocalizedChatApp.tsx
import { useState, useEffect } from "react";
import {
  CometChatUIKit,
  UIKitSettingsBuilder,
  CometChatLocalize,
  CalendarObject,
  CometChatConversations,
  CometChatMessageHeader,
  CometChatMessageList,
  CometChatMessageComposer,
} from "@cometchat/chat-uikit-react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import "@cometchat/chat-uikit-react/css-variables.css";

const LANGUAGES = [
  { code: "en-US", label: "English", flag: "🇺🇸" },
  { code: "es", label: "Español", flag: "🇪🇸" },
  { code: "fr", label: "Français", flag: "🇫🇷" },
  { code: "de", label: "Deutsch", flag: "🇩🇪" },
  { code: "ja", label: "日本語", flag: "🇯🇵" },
];

function LocalizedChatApp() {
  const [initialized, setInitialized] = useState(false);
  const [currentLang, setCurrentLang] = useState("en-US");
  const [selectedConversation, setSelectedConversation] = useState<CometChat.Conversation>();

  useEffect(() => {
    const UIKitSettings = new UIKitSettingsBuilder()
      .setAppId("APP_ID")
      .setRegion("REGION")
      .setAuthKey("AUTH_KEY")
      .build();

    CometChatUIKit.init(UIKitSettings).then(() => {
      // Initialize localization
      CometChatLocalize.init({
        language: "en-US",
        fallbackLanguage: "en-US",
        disableAutoDetection: false,
        calendarObject: new CalendarObject({
          today: "[Today at] hh:mm A",
          yesterday: "[Yesterday at] hh:mm A",
          lastWeek: "dddd",
          otherDays: "MMM DD, YYYY",
        }),
      });

      // Add custom translations
      CometChatLocalize.addTranslation({
        "en-US": { "app_title": "Support Chat" },
        "es": { "app_title": "Chat de Soporte" },
        "fr": { "app_title": "Chat Support" },
        "de": { "app_title": "Support-Chat" },
        "ja": { "app_title": "サポートチャット" },
      });

      CometChatUIKit.login("UID").then(() => {
        setInitialized(true);
      });
    });
  }, []);

  const handleLanguageChange = (langCode: string) => {
    CometChatLocalize.setCurrentLanguage(langCode);
    setCurrentLang(langCode);
  };

  const getConversationWith = () => {
    if (!selectedConversation) return null;
    const type = selectedConversation.getConversationType();
    if (type === "user") {
      return { user: selectedConversation.getConversationWith() as CometChat.User };
    }
    return { group: selectedConversation.getConversationWith() as CometChat.Group };
  };

  if (!initialized) return <div>Loading...</div>;

  const conversationWith = getConversationWith();

  return (
    <div style={{ height: "100vh", display: "flex", flexDirection: "column" }}>
      {/* Language Selector Header */}
      <div style={{ padding: "12px 16px", borderBottom: "1px solid #eee", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <h1 style={{ margin: 0, fontSize: 18 }}>
          {CometChatLocalize.getLocalizedString("app_title")}
        </h1>
        <select
          value={currentLang}
          onChange={(e) => handleLanguageChange(e.target.value)}
          style={{ padding: "8px 12px", borderRadius: 8, border: "1px solid #ddd" }}
        >
          {LANGUAGES.map((lang) => (
            <option key={lang.code} value={lang.code}>
              {lang.flag} {lang.label}
            </option>
          ))}
        </select>
      </div>

      {/* Chat UI */}
      <div style={{ flex: 1, display: "flex" }}>
        <div style={{ width: 400, borderRight: "1px solid #eee" }}>
          <CometChatConversations
            onItemClick={(conversation) => setSelectedConversation(conversation)}
          />
        </div>

        {conversationWith ? (
          <div style={{ flex: 1, display: "flex", flexDirection: "column" }}>
            <CometChatMessageHeader {...conversationWith} />
            <CometChatMessageList {...conversationWith} />
            <CometChatMessageComposer {...conversationWith} />
          </div>
        ) : (
          <div style={{ flex: 1, display: "grid", placeItems: "center", color: "#727272" }}>
            Select a conversation
          </div>
        )}
      </div>
    </div>
  );
}

export default LocalizedChatApp;

Methods

MethodDescription
init(settings)Initialize with configuration
setCurrentLanguage(code)Change language at runtime
getCurrentLanguage()Get current language code
getDefaultLanguage()Get system/fallback language
getBrowserLanguage()Detect browser language
addTranslation(translations)Add custom translations
getLocalizedString(key)Get translated string by key
formatDate(timestamp, calendarObject)Format a Unix timestamp

LocalizationSettings

PropertyTypeDescription
languagestringLanguage code (e.g., "en-US")
fallbackLanguagestringFallback if primary unavailable
disableAutoDetectionbooleanDisable browser language detection
timezonestringTimezone for dates (e.g., "America/New_York")
calendarObjectCalendarObjectCustom date/time formats
missingKeyHandler(key) => voidHandle missing translation keys

Report Message Reasons

Add translations for custom flag reasons:
CometChatLocalize.addTranslation({
  "en-US": {
    "flag_message_reason_id_dislike": "I just don't like it",
  },
  "es": {
    "flag_message_reason_id_dislike": "Simplemente no me gusta",
  },
});

Mention Labels

Add translations for custom mention labels:
CometChatLocalize.addTranslation({
  "en-US": {
    "message_composer_mention_channel": "channel",
  },
  "es": {
    "message_composer_mention_channel": "canal",
  },
});

Common Issues

Localization must be initialized after CometChatUIKit.init() completes. Configure it inside the init callback.
IssueSolution
Translations not showingEnsure addTranslation is called after CometChatUIKit.init()
Wrong language detectedSet disableAutoDetection: true and specify language explicitly
Date format not changingCheck timezone is set correctly in init config
Missing translation keyUse missingKeyHandler to log or handle missing keys
Component ignores global formatComponent-level CalendarObject overrides global settings
For more help, see the Troubleshooting Guide or contact CometChat Support.

Next Steps