Home > other >  ReactJS - having the second dropdown box data depend on the first selected dropdown box data?
ReactJS - having the second dropdown box data depend on the first selected dropdown box data?

Time:03-04

I have a state variable that looks rather complex.. like this:

[
    {
        objName: nameOne,
        objData: [
            {
                colName: [ colData ]
            },
            {
                colName: [ colData]
            }
        ]
    },
...
]

For the first dropdown box, the data displayed is all the objNames. And that works fine. But the second should display all the colNames based on which ever objName was selected. My problem is that the size of this is dynamic.

I basically just want to take what ever was selected and query the state variable like a dictionary and display all the column names. Is this possible?

I already have the code built out for the <select>s. But I just dont know how to handle this. Any ideas?

CodePudding user response:

The trick is to save the current selection (in the first dropdown) in the state of the component. I think this answer is useful here: https://stackoverflow.com/a/28868135/1326264

Then you can use this saved selection to populate the second dropdown.

CodePudding user response:

You will need to filter based on the first dropdown's value that is selected. So your second dropdown's object should have a value which matches something from the first dropdown's value. For example, lets you have a list of Countries and a list of cities.

const country = ['USA','UK', 'India']
const cities = [{name:'Los Angeles', country:'USA'},{name:'California', country:'USA'},{name:'London', country:'UK'}, {name:'Delhi', country:'India'}] 

Then you can update your cities state variable whenever the country state variable changes by putting in a useEffect

useEffect(() => {
    setCities(cities.filter(city => city.country === country))
},[country])
  • Related