Reputation: 151196
Using country-data, I thought I could do
npm install --save country-data
and then in the code:
import CountryData from "country-data";
and use
CountryData.countries["TW"]
to get the country data, and
CountryData.countries["TW"].name
to get the name. But CountryData.countries["TW"]
gets undefined
already. How can it be done? Are there possible better alternatives to using country-data
?
P.S. the npm page and github page of country-data has some info on how to use it with webpack, which I suspect is needed to be used with React. But I did them:
npm install json-loader --save-dev
add to webpack.config.js:
// ...
loaders: [
// other loaders
{ test: /\.json$/, loader: 'json' },
],
// ...
and it doessn't work yet.
Upvotes: 1
Views: 13416
Reputation: 610
Try country-list library
const { getCode, getName } = require('country-list');
console.log(getCode('Belgium')); // BE
console.log(getName('BE')); // Belgium
Upvotes: 3
Reputation: 126
If you use
var CountryData = require('country-data');
console.log(CountryData.countries['TW']);
It works an outputs as such
{ alpha2: 'TW',
alpha3: 'TWN',
countryCallingCodes: [ '+886' ],
currencies: [ 'TWD' ],
emoji: '🇹🇼',
ioc: 'TPE',
languages: [ 'zho' ],
name: 'Taiwan',
status: 'assigned' }
It could be because of how the module is exported?
This also works
import CountryData from 'country-data'
console.log(JSON.stringify(CountryData.countries['TW']));
Outputs as such
{"alpha2":"TW","alpha3":"TWN","countryCallingCodes":["+886"],"currencies":["TWD"],"emoji":"🇹🇼","ioc":"TPE","languages":["zho"],"name":"Taiwan","status":"assigned"}
Upvotes: 0
Reputation: 281932
It seems you are using the npm module
incorrectly
According to the docs you can do it as follows
npm install --save country-data
And import it like
import {countries} from 'country-data';
and then use it like
console.log(countries["TW"].name);
Upvotes: 3