Skip to main content
Version: v6

Localization

Overview

React UI Kit provides multi-language localization to adapt the UI elements based on the user's preferred language settings. The CometChatLocalize class allows developers to:

  • Automatically detect and apply a language based on browser/device settings.
  • Manually change the UI language.
  • Format date and time based on localization settings.

The v6 React UI Kit expands support for multiple languages and allows developers to define custom translations.
The localization system now includes language JSON files, which store translations, and an improved CometChatLocalize class, which handles language detection and formatting.


Supported Languages

React UI Kit currently supports 19 languages:

LanguageCode
English (United States)en-US
English (United Kingdom)en-GB
Dutchnl
Frenchfr
Germande
Hindihi
Italianit
Japaneseja
Koreanko
Portuguesept
Russianru
Spanishes
Turkishtr
Chinesezh
Chinese (Traditional)zh-TW
Malayms
Swedishsv
Lithuanianlt
Hungarianhu

🔗 View JSON files for all supported languages in the GitHub repository:
Language JSON Files


CometChatLocalize

The CometChatLocalize class provides methods for managing localization in the UI Kit.

🔗 View full class file in the GitHub repository:
CometChatLocalize


LocalizationSettings

The LocalizationSettings interface defines various localization settings for an application or component. It allows developers to configure the language, translations, time zone, and calendar formatting while providing options for automatic detection and missing key handling.

PropertyTypeDescription
languagestringThe language code (e.g., "en", "fr") for the current localization.
translationsForLanguage{ [key: string]: any }An object containing key-value pairs for translations in the current language.
disableAutoDetectionbooleanDisables automatic language detection based on the browser or device settings.
fallbackLanguagestringThe fallback language code to use if the primary language is not available.
disableDateTimeLocalizationbooleanDisables localization for date and time values, forcing the default format.
timezonestringThe timezone used for date and time formatting (e.g., "America/New_York", "Europe/London").
calendarObjectCalendarObjectA custom calendar format using CalendarObject to define localized date and time formatting.
missingKeyHandler(key: string) => stringA function that handles missing translation keys, allowing custom error handling or fallbacks.

Example

import { CometChatLocalize } from "@cometchat/chat-uikit-react";
import { CalendarObject } from "./CalendarObject";

CometChatLocalize.init({
language: "es", // Default language set to Spanish
fallbackLanguage: "en-US", // Use English if the preferred language is not available
translationsForLanguage: {
"es": {
"welcome_message": "¡Bienvenido a CometChat!",
"logout_message": "Has cerrado sesión con éxito."
},
"fr": {
"welcome_message": "Bienvenue sur CometChat!",
"logout_message": "Vous vous êtes déconnecté avec succès."
}
},
disableAutoDetection: false, // Allow automatic detection of browser/device language
disableDateTimeLocalization: false, // Enable localization for date and time
timezone: "Europe/Madrid", // Set time zone for date and time formatting
calendarObject: new CalendarObject({
today: "[Hoy a las] hh:mm A",
yesterday: "[Ayer a las] hh:mm A",
lastWeek: "[Última semana el] dddd",
otherDays: "DD MMM YYYY, hh:mm A",
relativeTime: {
minute: "%d minuto atrás",
minutes: "%d minutos atrás",
hour: "%d hora atrás",
hours: "%d horas atrás",
}
}),
missingKeyHandler: (key) => `🔍 Missing translation for: ${key}`, // Custom handler for missing translations
});


CalendarObject

The CalendarObject class defines customizable formatting for date and time representation. It allows you to format dates based on whether they are today, yesterday, last week, or other days. It also supports relative time formatting for minutes and hours.

Important Notice

Changing this format will globally update the date and time representation wherever it is used in the component.
However, if a component-specific CalendarObject is provided, it will take higher precedence over the global settings.

PropertyTypeDescription
todaystringCustom formatting for dates that fall on the same day. Example: "Today at hh:mm A"
yesterdaystringCustom formatting for dates that fall on the previous day. Example: "Yesterday at hh:mm A"
lastWeekstringCustom formatting for dates within the last 7 days. Example: "Last week on dddd"
otherDaysstringCustom formatting for dates that do not fit other categories. Example: "DD MMM YYYY, hh:mm A"
relativeTimeobjectCustom formatting for relative time expressions (e.g., "2 hours ago").
relativeTime.minutestringFormatting for a single minute. Example: "%d minute ago"
relativeTime.minutesstringFormatting for multiple minutes. Example: "%d minutes ago"
relativeTime.hourstringFormatting for a single hour. Example: "%d hour ago"
relativeTime.hoursstringFormatting for multiple hours. Example: "%d hours ago"

Example

import { CometChatLocalize } from "@cometchat/chat-uikit-react";
import { CalendarObject } from "./CalendarObject";

new CalendarObject({
today: "[Hoy a las] hh:mm A",
yesterday: "[Ayer a las] hh:mm A",
lastWeek: "[Última semana el] dddd",
otherDays: "DD MMM YYYY, hh:mm A",
relativeTime: {
minute: "%d minuto atrás",
minutes: "%d minutos atrás",
hour: "%d hora atrás",
hours: "%d horas atrás",
}
})

Methods

Initialize CometChatLocalize

This method initializes the localization system with default values and optional configurations.

Usage

  • Set the default language, timezone, and fallback settings.
  • Define a custom calendar format if required.
  • Customize how missing keys are handled.

Example

import { CometChatLocalize } from "@cometchat/chat-uikit-react";

// Initialize localization settings
CometChatLocalize.init({
language: "es", // Default language: Spanish
fallbackLanguage: "en-US", // Fallback if translation is missing
disableAutoDetection: false, // Enable browser language detection
timezone: "Europe/Madrid",
missingKeyHandler: (key) => `Missing translation: ${key}`,
});


Get Browser Language

This method detects the language set in the user's browser or device settings.

Usage

  • Automatically set the app’s language based on the user’s browser settings.
  • Helps in making the UI multilingual without requiring user input.

Example

const userLang = CometChatLocalize.getBrowserLanguage();
console.log(userLang);

Get Localized String

This method fetches localized text based on the current language.

Usage

  • Retrieve translations dynamically without hardcoding values in multiple languages.
  • Useful for UI elements, buttons, alerts, and system messages.

Example

const translatedText = CometChatLocalize.getLocalizedString("welcome_message");

Get Current Language

This method returns the currently set language for the UI Kit.

Usage

  • Useful to debug and display the currently active language.
  • Helps when dynamically switching between languages.

Example

console.log(CometChatLocalize.getCurrentLanguage());

Get Default Language

This method returns the system-preferred language.

Usage

  • If disableAutoDetection is enabled, the method returns the fallback language.
  • If auto-detection is enabled, it returns the browser's preferred language.

Example

console.log(CometChatLocalize.getDefaultLanguage());

Set Current Language

This method updates the language at runtime without reloading the application.

Usage

  • Allow users to change the language via a settings menu.
  • Ensure that UI elements are updated instantly after changing the language.

Example

CometChatLocalize.setCurrentLanguage("fr");

Add Custom Translations

This method allows you to add custom translations to the existing ones dynamically. It ensures that new translations are merged into the existing localization data.

Usage

  • You can define custom translation keys and override the existing translations.
  • You can add new languages to the existing translations.
  • Useful when you want to support additional words or phrases not present in the default language files.

Example

CometChatLocalize.addTranslation({
"en-US": { "welcome_message": "Welcome to CometChat!" }
});

Customisation

CometChat UI Kit provides flexible customization options for date/time format. Users can configure global settings using CometChatLocalize.init() or pass a CalendarObject directly to individual components for component-specific customization.

  • Global Configuration: When settings are provided in CometChatLocalize.init(), all UI components will automatically use the configured date/time formats.
  • Component-Specific Configuration: If a CalendarObject is passed to a component, it overrides the global settings and applies only to that specific instance.

Global Configuration Example

To apply a custom date format globally across the whole UI Kit.

CometChatLocalize.init({
calendarObject:new CalendarObject({
today: " hh:mm A",
yesterday: "[Yesterday],
otherDays: "DD MMM YYYY, hh:mm A"
})
});

Component-Specific Customization Example

To apply a custom date format only within a specific component.

<CometChatMessageHeader 
group={groupObj}
lastActiveAtDateTimeFormat={new CalendarObject({
today: "[Today at] hh:mm A",
yesterday: "[Yesterday at] hh:mm A",
otherDays: "DD MMM YYYY, hh:mm A"
})}
/>