📅  最后修改于: 2023-12-03 15:14:14.945000             🧑  作者: Mango
React Native provides a way to develop cross-platform mobile applications for both iOS and Android. In this article, we will explore how to use countries code in React Native.
There are several APIs available for getting countries code, some of them are:
In this article, we will use the Rest Countries API to get the country codes.
To get data from an API in React Native, we need to install the axios library. It can be installed by running the following command:
npm install axios
To get the list of countries with their codes, we can use the following code snippet:
import axios from 'axios';
export const getCountriesCode = async () => {
const { data } = await axios.get('https://restcountries.com/v2/all?fields=name,alpha2Code,alpha3Code');
return data;
};
This code uses the axios library to get data from the Rest Countries API. The getCountriesCode
function returns an array of objects with the name
, alpha2Code
, and alpha3Code
fields.
To display the list of countries with their codes, we can use the following code snippet:
import React, { useState, useEffect } from 'react';
import { Text, View } from 'react-native';
import { getCountriesCode } from './api';
const CountriesCodeScreen = () => {
const [countries, setCountries] = useState([]);
useEffect(() => {
const fetchCountriesCode = async () => {
const countriesCode = await getCountriesCode();
setCountries(countriesCode);
};
fetchCountriesCode();
}, []);
return (
<View>
{countries.map((country, index) => (
<View key={index}>
<Text>{country.name}</Text>
<Text>{country.alpha2Code}</Text>
<Text>{country.alpha3Code}</Text>
</View>
))}
</View>
);
};
export default CountriesCodeScreen;
This code defines a screen component that uses the getCountriesCode
function to get the countries code and set them to the countries
state variable. It then maps over the countries
array to display the country name, alpha2Code, and alpha3Code.
In this article, we explored how to use countries code in React Native using the Rest Countries API. We installed the axios library to get data from the API and displayed the list of countries with their codes on the screen.