Reputation: 405
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.
Upvotes: 7
Views: 9669
Reputation: 123
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.
Upvotes: 4
Reputation: 23
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
Upvotes: 2
Reputation: 405
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!
Upvotes: 9