Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use i18n-iso-countries in React?

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.

like image 968
jupiterjelly Avatar asked Mar 03 '23 09:03

jupiterjelly


2 Answers

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!

like image 181
jupiterjelly Avatar answered Mar 11 '23 02:03

jupiterjelly


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

like image 25
Lotttttte Avatar answered Mar 11 '23 02:03

Lotttttte