react-i18next - detecting if fallback language was used

Viewed 554

I'm developing component to track missing translations and my goal is to style missing translations with styled components but i can't find a way to detect if t("someKey") returns translated value from currently set language or default fallback if it's missing. Any ideas? Docs are not helpful at this point.

2 Answers

Our team solved it partially (edit: at least for token missing entirely, not yet when it uses the fallback language). The configuration is actually at i18next level, see: https://www.i18next.com/overview/configuration-options.

Here is the solution when using next-i18next (v8 at the time I write this). Be careful that you need the i18n config to be serializable in this scenario (https://github.com/isaachinman/next-i18next#unserialisable-configs).

This function is expected to run client-side, so you may use @sentry/browser.

// NOTE: next-i18next.config.js is a JS file, so no TypeScript here
const Sentry = require("@sentry/browser");

module.exports = {
  // @see https://www.i18next.com/overview/configuration-options
  i18n: {
    defaultLocale: "en",
    locales: ["en", "fr", "de", "tr"],
    localeDetection: false, 
    // Set to true to enable the missingKeyHandler callback
    saveMissing: true,
    // Method triggered client-side when a token is missing
    // It will still respect your fallback language, 
    // but let you add a side-effect like calling Sentry
    missingKeyHandler: (
      ngs,
      ns,
      key,
      fallbackValue,
      updateMissing,
      options
    ) => {
      Sentry.captureException(new Error("Missing i18n key"), {
        extra: { ngs, ns, key, fallbackValue, updateMissing, options },
      });
    },

I'm really inexperienced with this so the only solution I found so far is to disable the fallback and navigate through the pages. The debugger will tell you the errors.

Related