I created a React country and state field package that can detect the user's IP geolocation
Table of contents
For users, picking their countries from a long list of options in the country field is quite an annoying thing. To solve the UX issue, I created a country and state field package for React developers.
The fields can detect the user's IP geolocation, and set the country and state automatically so the user doesn't have to do anything. It also supports a state list based on the selected country. Here is an example of how it works in action.
I live in Sydney (New South Wales, Australia). The fields will automatically detect where I am and set it to the correct options. But if I want to pick a different country and state, the UI is also user-friendly.
Installation
Run npm i react-country-state-fields
to install the components in your React project.
Use the field components
import { CountryField, StateField, VisitorAPIComponents } from 'react-country-state-fields';
import React, { useState } from 'react';
export const MyForm = () => {
const [country, setCountry] = useState({}); // the selected country
const [state, setState] = useState({}); // the selected state
const visitorApiPrjectId = ""; // assign your project ID here
return(
<VisitorAPIComponents projectId={visitorApiPrjectId} handleCountryChange={(countryObj) => setCountry(countryObj)} handleStateChange={(stateObj) => setState(stateObj)}>
<CountryField label="Country/Territory"></CountryField>
<StateField label="State/Province"></StateField>
</VisitorAPIComponents>
);
}
The <VisitorAPIComponents />
component detects the IP location using a server-side API called VisitorAPI. You will need to create a free or paid project, and grab the project ID to fill the projectId
prop to enable the location detection feature of the fields. Don't forget to add your domains to the authorized domain list of your project or the API will return an error.
In the example code, the country object and the state object will be stored in the country
and the state
states. To access the country name (e.g. "Australia"), use country.label
. For the country code (e.g. "AU"), use country.code
. Same as the state
state, there are label
and code
properties.
Resources
Github: https://github.com/visitorapi/react-country-state-fields
Example: https://github.com/visitorapi/react-country-state-fields-example/blob/main/src/App.js
NPM package: https://www.npmjs.com/package/react-country-state-fields
Subscribe to my newsletter
Read articles from Chaoming Li directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by