Reputation: 490
I get a backend data structure as following.
{
"courseDetails" :
[{"departmentId" : 105654,
"courses" :
[{"stream" : "science","courseIds" : ["104","105","106"]},
{"stream" : "art","courseIds" : ["102", "103"]}]
},
{"departmentId" : 105655,
"courses" :
[{"stream" : "commerce","courseIds" : ["101", "100"]}]
}
]
}
In the UI, I have three dropdown lists.
Department ID | Stream | Course ID
First Department ID dropdown list should be populated with departmentIDs 105654 and 105655. When department id 105654 is selected, Stream dropdown list should be populated as science and art. When science is selected from this second dropdown list, course ids should be populated in third dropdown list as 104, 105, 106.
The json data structure above is to have all data at once so that I don't have to make backend call each time a dropdown option is selected.
How can I achieve this using react js? I am new to it.
Upvotes: 0
Views: 1081
Reputation: 2257
I would like to use 3 react-select for 3 dropdown list and connect them based on the selected value of one another. the state will look like your provided data and three flag for three dropdown fields.
dropdown1: true, dropdown2: false, dropdown3: false
The render will look like:
{this.state.dropdown1 ? <Select options=[all the Department ID] onChange={handleSelectDepartment} />: null}
{this.state.dropdown2 ? <Select options=[course corresponding stream ] onChange={handleSelectStream} />: null}
{this.state.dropdown3 ? <Select optons=[Stream corresponding courseID ] onChange={handleSelectCourse} />: null}
So first the dropdown list of Department will be visible only. On selecting a value in dropdown list of Department i would set the dropdown2 state to true and it will make the dropdown list of Stream visible and so on..
Upvotes: 0
Reputation: 798
Assuming that you receive data in data
and your dropdown components each accept an array that must be inserted in their respective dropdown menus, you get the arrays like this:
const Department = data.courseDetails.map(obj => obj.departmentId);
Now assuming you have some departmentId selected, you can do:
const streams = data.courseDetails.filter(x => x.departmentId === departmentId)[0].courses.map(obj => obj.stream)
Now assuming you have the stream stored in streamId, you can do:
const courseIds = data.courseDetails.filter(x => x.departmentId === departmentId)[0].courses.filter(x => x.stream === streamId)[0].courseIds;
You should store each array in a state and pass on that state as a prop to the corresponding dropdown components.
Upvotes: 2