最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use i18n-iso-countries in React? - Stack Overflow

programmeradmin0浏览0评论

I'm working on a React app and trying to use the i18n-iso-countries package to get a countries object in English which has keys as iso codes and values as the country names. This is easy in node, as I've verified with a simple script running the way the i18n-iso-countries npm docs show, like this:

const countries = require("i18n-iso-countries");
console.log(countries.getNames('en'));

But when I do this in my react app (made with create-react-app) like this ...

import countries from "i18n-iso-countries";
console.log(countries.getNames('en'));

...I get an empty object back. When I log just countries (console.log(countries)) in React, I see the function "getNames" on it and the other functions the docs mention, so I'm not sure what gives.

I'm working on a React app and trying to use the i18n-iso-countries package to get a countries object in English which has keys as iso codes and values as the country names. This is easy in node, as I've verified with a simple script running the way the i18n-iso-countries npm docs show, like this:

const countries = require("i18n-iso-countries");
console.log(countries.getNames('en'));

But when I do this in my react app (made with create-react-app) like this ...

import countries from "i18n-iso-countries";
console.log(countries.getNames('en'));

...I get an empty object back. When I log just countries (console.log(countries)) in React, I see the function "getNames" on it and the other functions the docs mention, so I'm not sure what gives.

Share Improve this question asked Sep 27, 2019 at 14:23 jupiterjellyjupiterjelly 4053 silver badges15 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 9

Just needed to add this line!

countries.registerLocale(require("i18n-iso-countries/langs/en.json"));

Not sure why this needs to be added in React (and Angular - where I found answer How to use i18n-iso-countries in Angular 6 - and probably other ui libraries/frameworks) so if someone could explain that, that would be cool, but hey, at least it's working!

Without using require it looks like this:

import frLocale from 'i18n-iso-countries/langs/fr.json'

countries.registerLocale(frLocale)
const countryObj = countries.getNames('fr', 'official')

Replace frLocale and fr by whatever local / language you like.

It is a little bit to late. But to answer jupiterjelly this line is needed for browser environment, so that your bundler knows that it needs to put this file in the bundle

发布评论

评论列表(0)

  1. 暂无评论