Skip to content

Instantly share code, notes, and snippets.

@anburocky3
Created May 11, 2024 11:58
Show Gist options
  • Save anburocky3/b33be3a2f10a2f5e84e6edbf8c996b5f to your computer and use it in GitHub Desktop.
Save anburocky3/b33be3a2f10a2f5e84e6edbf8c996b5f to your computer and use it in GitHub Desktop.
Get Country > State > City using country-state-city package - ReactJS
import { Country, State, City } from 'country-state-city';
import { ICountry, IState, ICity } from 'country-state-city'
const App = () => {
const [country, setCountry] = useState(Country.getAllCountries())
const [countryState, setCountryState] = useState<IState[]>([])
const [city, setCity] = useState<ICity[]>([])
useEffect(() => {
setCountryState(State.getStatesOfCountry(data.country));
}, [data.country])
useEffect(() => {
console.log(City.getCitiesOfState(data.country, data.state), data.country, data.state)
setCity(City.getCitiesOfState(data.country, data.state));
}, [data.state])
return (
<div className="row">
<div className="col">
<div className="form-group">
<InputLabel htmlFor="country" value="Country (நாடு):"
required />
<Select className="" id="country" name="country"
placeholder={'Select Country'}
options={
[...country.map((item, index) => (
{value: item.isoCode, label: capitalizeFirstLetter(item.name)}
))]
}
noOptionsMessage={({inputValue}) => `No country found for "${inputValue}"`}
onChange={(e) => {
setData('country', e!.value)
}} />
<InputError message={errors.country} className="mt-2" />
</div>
</div>
<div className="col">
<div className="form-group">
<InputLabel htmlFor="state" value="State (மாநிலம்):"
required />
<Select className="" id="state" name="state"
placeholder={'Select State'}
options={
[...countryState.map((item, index) => (
{value: item.isoCode, label: capitalizeFirstLetter(item.name)}
))]
}
noOptionsMessage={({inputValue}) => `No state found for "${inputValue}"`}
onChange={(e) => {
setData('state', e!.value)
}} />
<InputError message={errors.state} className="mt-2" />
</div>
</div>
<div className="col">
<div className="form-group">
<InputLabel htmlFor="city" value="City (நகரம்):"
required />
<Select className="" id="city" name="city"
placeholder={'Select City'}
options={
[...city.map((item, index) => (
{
value: item.name.toLowerCase(),
label: capitalizeFirstLetter(item.name)
}
))]
}
noOptionsMessage={({inputValue}) => `No city found for "${inputValue}"`}
onChange={(e) => {
setData('city', e!.value)
}} />
<InputError message={errors.city} className="mt-2" />
</div>
</div>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment