1

I have a language selector in my application that allows users to select their desired display language for the app. Right now, I only have a few options, but we are planning to add more in the future. I would like to dynamically generate the settings page language options based on what we translations we have available.

I am very close to a solution, but I'm running into a snag. I can generate the list of languages available to i18next using this code:

const availableLocales = Object.keys(i18next.services.resourceStore.data);

but that leaves me with an issue. I'd like to display the names of these languages to the user dynamically, e.g. en becomes English, de becomes Deutsch etc. How can I achieve this?

<RadioGroup
  aria-labelledby="language-select-group"
  value={i18n.language}
  name="language-select-group"
  onChange={handleChange}
>
  {availableLocales.map((languageCode) => (
    <FormControlLabel
      value={languageCode}
      control={<Radio />}
      label={/* TODO: What code goes here? */}
    />
  ))}
</RadioGroup>
Chase Sandmann
  • 4,795
  • 3
  • 30
  • 42
  • 1
    Related question: [How do you convert a language code to the language name in JavaScript?](https://stackoverflow.com/questions/25131388/how-do-you-convert-a-language-code-to-the-language-name-in-javascript) – Yogi Sep 29 '22 at 22:20

1 Answers1

3

I figured out a way to do this with native JavaScript using Intl.DisplayNames. It's not super pretty, but it is fairly concise, works on all modern browsers (not including IE) and requires no additional libraries.

<RadioGroup
  aria-labelledby="language-select-group"
  value={i18n.language}
  name="language-select-group"
  onChange={handleChange}
>
  {availableLocales.map((languageCode) => {
    const nameGenerator = new Intl.DisplayNames(languageCode, { type: 'language' });
    const displayName = nameGenerator.of(languageCode);
    return (
      <FormControlLabel
        value={languageCode}
        control={<Radio />}
        label={displayName}
      />
    );
  ))}
</RadioGroup>
Chase Sandmann
  • 4,795
  • 3
  • 30
  • 42