Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-i18next - detecting if fallback language was used

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.

like image 343
user6204214 Avatar asked Nov 07 '22 09:11

user6204214


1 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 },
      });
    },
like image 98
Eric Burel Avatar answered Nov 26 '22 11:11

Eric Burel