I have 2 JSON files that contain data for regions and provinces respectively.
Here is a sample data for my regions.json
[
{
"id": 1,
"long_name": "First region in the country",
"name": "firstRegion",
"key": "FR"
},
{
"id": 2,
"long_name": "Second region in the country",
"name": "secondRegion",
"key": "SR"
}
]
And this is my provinces.json
[
{ "id": 1, "name": "province One", "region_key": "FR", "key": "p1" },
{ "id": 2, "name": "province Two", "region_key": "SR", "key": "p2" },
{ "id": 3, "name": "province Three", "region_key": "FR", "key": "p3" },
{ "id": 4, "name": "province Four", "region_key": "SR", "key": "p4" }
]
What I want to happen is when the user chooses a region from the first dropdown, for example, First region in the country, the second dropdown, which is the provinces dropdown, must be dynamically populated with the provinces that belong to First region in the country or provinces with the region_key FR. From this logic, I assume there must be some mapping that could happen. I referred to one of the answers here but unfortunately, when I try to edit the options value from the provinces' selectcomponent, I get an error props.options.map is not a function. Also, my JSON files, I assume, need a different style for mapping? Since I need to match the key from regions.json to region.key in provinces.json but I'm fairly new to rendering data from the database to the front-end using React.
Here is a code snippet for my dropdown:
/* Dropdown for Regions */
<h4 className="mb-3 text-sm">Regions</h4>
<Select
className="basic-multi-select text-sm"
classNamePrefix="select"
defaultValue={selectedRegions}
getOptionLabel={(region) => region.long_name}
getOptionValue={(region) => region.id}
isMulti
name="regions"
options={regions}
onChange={handleChangeRegion}
placeholder="Region select"
/>
/* Dropdown for Provinces */
<h4 className="mb-3 text-sm">Provinces</h4>
<Select
className="basic-multi-select text-sm"
classNamePrefix="select"
defaultValue={selectedProvinces}
getOptionLabel={(province) => province.name}
getOptionValue={(province) => province.id}
isMulti
name="provinces"
options={provinces}
onChange={handleChangeProvince}
placeholder="Province Select"
/>
This is my handleChangeRegion, for context.
const handleChangeRegion = (selectedRegions) => {
setSelectedRegions([...selectedRegions])
regionID = []
for (var i = 0; i < Object.keys(selectedRegions).length; i++) {
regionID[i] = selectedRegions[i].id
}
}