How to update one select option on change of other in react hooks

Viewed 75

I have a set of data by which I want to update my UI select option but I don't have any idea how I can do that

JSON data

[
{
    country: 'India',
    cities: [
        {
            city_name: 'New delhi',
        },
        {
            city_name: 'mumbai',
        },
    ],
},
{
    country: 'England',
    cities: [
        {
            city_name: 'London',
        },
        {
            city_name: 'manchester',
        },
    ],
},
{
    country: 'Portugal',
    cities: [
        {
            city_name: 'Lisbon',
        },
    ],
},
];

What I've tried is :

                   <select
                        name="country">
                        {data.map((li, index) => (
                                <option
                                    key={index}
                                    value={li.country}
                                    onchange={() => onchange_device(li.country)}>
                                    {li.country}
                                </option>
                            ))}
                    </select>


                 <select
                                name="city">
                                <option
                                    value="city val
                                    >
                                    here I want to show city
                                </option>
                            ))}
                    </select>

I am trying to do on-change, but first of all I want to show first option as selected and there sub cities should also be selected next, I don't have any idea how to do this

My code sand box

1 Answers

You need to refactor onchange to onChange. You need to assign this prop to the select element rather than the option elements.

<select name="Country" onChange={(e) => onchange_device(e.target.value)}>

Afterwards, you can have a state that keeps track of the cities options based on the country that you have selected

const [cityOptions, setCityOptions] = React.useState(data[0].cities); // " I want to show first option as selected"

Then just map between the values

<div className="App">
  <select name="Country" onChange={(e) => onchange_device(e.target.value)}>
    {data.map((li, index) => (
      <option key={index} value={li.country}>
        {li.country}
      </option>
    ))}
  </select>
  <select name="city">
    {cityOptions.map((city, index) => (
      <option key={index} value={city.city_name}>
        {city.city_name}
      </option>
    ))}
  </select>
</div>

Edit ecstatic-monad-oobyn

Related