React Cascading Dropdowns (Dynamic)

Viewed 26

The scenario is as follows: I want to make a reusable cascading dropdown component, however every video/article that I've seen on the topic just uses hard coded dependent dropdowns such as: Country => State => City.

However, for my situation it will not always be the same dependencies. How can I support custom dependency for cascading dropdowns?

For a hardcoded example I would do something along the lines of having one useEffect for each of the options, and make the dependant options change when the parent changes.

I have an object example to iterate through of one page I am trying to accomplish this for:

[
  {
    key: 0,
    name: "State",
    parentQuestion: null,
    inputType: "Dropdown",
  },
  {
    key: 1,
    name: "Sublocation",
    parentQuestion: "State",
    inputType: "Dropdown",
  },
  {
    key: 2,
    name: "Operation",
    parentQuestion: "Sublocation",
    inputType: "Dropdown",
  },
  {
    key: 3,
    name: "Installment Number",
    parentQuestion: "Operation",
    inputType: "Dropdown",
  },
  {
    key: 4,
    name: "Upload Directory",
    parentQuestion: null,
    inputType: "File",
  },
  {
    key: 5,
    name: "Download Directory",
    parentQuestion: null,
    inputType: "Directory",
  },
]

Is it possible to accomplish this? Or must I hardcode the logic with different hooks for each page?

1 Answers

You can have the component built passing the array data as props, then iterating over each key on an element of the array, you have to build the selects using map. For the option values list you have to prepare another object such that

optionList={country:[],state:[],city:[]}

You have to maintain an object with selected options, and onchange of the selects you have to modify the object for selected options.

Edit Also onchange of selects you have to modify the optionList object, reducing the options array, for example

if country is selected 'UK' then on the final object selected you add the value final_object={country:'UK'} and then in optionList you have to reduce the options for corresponding state and city

Related