Issue
Using the repo here: https://github.com/country-regions/country-region-data/blob/master/data.js I am trying to map out the countries and cities related to that country. I am unsure on how to approach this if anyone has any advice.
I want it so that if a user selects a country, the cities field only shows regions related to that country if that makes sense?
This is my code below currently, I use a map to map out the countries. But I am unsure of how to map out the regions from the country selected?
<IonItem>
<IonLabel position={"stacked"}>Country</IonLabel>
<IonSelect interface="popover" value={values.country} name="country" placeholder="Select A Country" onIonChange={handleInputChange}>
{countries.map((country) => (
<IonSelectOption value={country.countryName} key={country.countryShortCode}>{country.countryName}</IonSelectOption>
))};
</IonSelect>
</IonItem>
<IonItem>
<IonLabel position={"stacked"}>City</IonLabel>
<IonSelect interface="popover" value={values.city} name="city" placeholder="Select A City" onIonChange={handleInputChange}>
{countries.map((country) => (
<IonSelectOption value={country.countryName} key={country.countryShortCode}>{country.countryName}</IonSelectOption>
))};
</IonSelect>
</IonItem>
Solution
I recommend creating another state variable to have the regions of the selected country.
Then, in the function handleInputChange
, you can assign the regions of the selected country to the variable.
Example:
function handleInputChange(e) {
const { value, name } = e.currentTarget;
if (name === 'country') {
const selectedCounty = countries.find(county => country.countryName === value);
setRegions(selectedCounty.regions);
}
}
------------ Rest of the code --------------------
<IonItem>
<IonLabel position={"stacked"}>Country</IonLabel>
<IonSelect interface="popover" value={values.country} name="country" placeholder="Select A Country" onIonChange={handleInputChange}>
{countries.map((country) => (
<IonSelectOption value={country.countryName} key={country.countryShortCode}>{country.countryName}</IonSelectOption>
))};
</IonSelect>
</IonItem>
<IonItem>
<IonLabel position={"stacked"}>City</IonLabel>
<IonSelect interface="popover" value={values.city} name="city" placeholder="Select A City" onIonChange={handleInputChange}>
{regions.map((region) => (
<IonSelectOption value={region.name} key={region.shortCode}>{region.name}</IonSelectOption>
))};
</IonSelect>
</IonItem>
Answered By - Diogozx
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.