import { View, Text } from 'react-native'
import React, { useEffect, useState } from 'react'
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import LogInviaPhone from '../Screens/LogInviaPhone';
import LogInviaEmail from '../Screens/LogInviaEmail';
import OTPScreen from '../Screens/OTPScreen';
import OTPScreenEmail from '../Screens/OTPScreenEmail';
import HomeScreen from '../Screens/HomeScreen';
import * as RNLocalize from 'react-native-localize';
import ISO3166 from 'iso-3166-1-alpha-2';
const Stack=createNativeStackNavigator();
export default function Navigation() {
const [country,setCountry]=useState(null);
useEffect(()=>{
const fetchCountry=async()=>{
try{
const locales = RNLocalize.getLocales();
const countryCode = locales[0]?.countryCode;
const countryName = ISO3166.getCountry(countryCode);
setCountry(countryName);
}catch(error){
console.log('Error fetching country:', error);
}
}
fetchCountry();
},[]);
useEffect(() => {
console.log("Country ",country); // Log the country name whenever it changes
}, [country]);
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name='Phone Login' component={LogInviaPhone} options={{
headerShown:false
}}/>
<Stack.Screen name='Email Login' component={LogInviaEmail} options={{
headerShown:false
}}/>
<Stack.Screen name='OTP Phone' component={OTPScreen} options={{
headerShown:false
}}/>
<Stack.Screen name='OTP Email' component={OTPScreenEmail} options={{
headerShown:false
}}/>
<Stack.Screen name='Home' component={HomeScreen} options={{
headerShown:false
}}/>
</Stack.Navigator>
</NavigationContainer>
)
}
I am getting united states in result but I am in india so it is not giving appropriate result what should I do. Is there any other package for this purpose. I am making a react native app where when user open the app first he has to login and if he is from india then app will open login with phone number and if he is from outside of india then app will open login with email.
According to the documentation of react-native-localize the method get the country is based on device locales not on device position, so, if you set English-US, you will get US as Country Code.
To get the current device location, you have two options, either get the IP Address and use API like ipapi.co or get the country code based on the GeoLocation of device.
Method One (using IP Address):
Install react-native-network-info and axios create a function to get IP Address and get the country code:\
Method Two:
This will require to get the current location of the user, get it's Latitude and Longitude and do some Reverse GeoCoding
Also give this react-native-device-country a try it will get the device country based on the SIM Card (telephony) settings.