简体   繁体   中英

How do I translate a locale code to language name using i18next

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, eg 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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM