2

I've built a site that translates nicely between en and zh locales, using a select element. Now, I'd like to have my code choose the initial locale based on the value of navigator.language. This led to my realization that my locale is en-US, not en. When I applied that value to the locale property of <IntlProvider />, a lot of new errors were thrown.

Error: [React Intl Error MISSING_TRANSLATION] Missing message: "details.reference" for locale "en-US", using default message as fallback.

The UI still looked fine, since the default messages were in English. And I'm guessing that these errors are silenced in production.

But, the same issue occurs in Chinese. If a user has their OS/browser locale set to zh-HK, react-intl displays the default messages (in English) instead of the translations in zh.json.

Is there a clever way to fix this? I know that I could clip the geography part of a locale off before passing it to <IntlProvider />, but that seems hackier than necessary...

carpiediem
  • 1,918
  • 22
  • 41

1 Answers1

0

I wrote a function to get around the problem for now, but hoping to find a better solution.

const [locale, setLocale] = React.useState(getBrowserLocale());

...

<IntlProvider locale={locale} messages={messages[locale]}>

// @see https://tools.ietf.org/rfc/bcp/bcp47.txt

function getBrowserLocale() {
  switch (navigator.language) {
    case "zh":
    case "zh-Hant":
    case "zh-Hans":
    case "zh-TW":
    case "zh-HK":
    case "zh-CN":
      return "zh";
    // case "zh-CN":
    //   return "zh-CN";
    default:
      return "en";
  }
}

export default getBrowserLocale;

carpiediem
  • 1,918
  • 22
  • 41
  • 1
    You could use the following: `const locale = navigator.language.slice(0, 2)` Edit: just saw that you said this was hacky. Yea I agree, it sort of is, but it does provide the exact functionality you're looking for. – Tyler Nov 13 '20 at 17:11