Search code examples
jsonajaxreactjsdropdown

ReactJS populate dropdown list based on first dropdown list selected value with ajax


So I came across this post regarding this similar question, https://stackoverflow.com/a/48078627 the answer was correct but it is in javascript, how can I transform it into the way how react will handle this piece of code.

Below is the code in javascript

<select id="sel" onchange="ChangeList()"> 
  <option value="">select</option> 
  <option value="I">Integer</option> 
  <option value="A">Alphabet</option> 
</select> 

<select id="type"></select> 

<script>
var IntandAlph = {};
IntandAlph['I'] = ['1', '2', '3','4','5','6','7','8','9','10'];
IntandAlph['A'] = ['A', 'B', 'C', 'D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];

function ChangeList() {
    var selList = document.getElementById("sel");
    var typeList = document.getElementById("type");
    var seltype = selList.options[selList.selectedIndex].value;
    while (typeList.options.length) {
        typeList.remove(0);
    }
    var Num = IntandAlph[seltype];
    if (Num) {
        var i;
        for (i = 0; i < Num.length; i++) {
            var sel = new Option(Num[i], i);
            typeList.options.add(sel);
        }
    }
} 
</script>

</body>
</html>

I am new to React and web development as well, it would be great if you can enlighten me on this issue. Thanks a lot in advance.


Solution

  • I have created a sample using useState and useEffect hooks to achieve the desired behavior, but there are plenty other ways to do it.

    At start, I am declaring options as a constant object, with keys equal to the values of the the first select.

    EDIT 2: After author's request, I've updated my sample fetching data from remote server instead of using a constant.

    Then using useState I handle the user selection of the first select. When this value change, I look into my data state, for the appropriate array of data.

    I strongly recommend you to take a look to React hooks for more details.

    EDIT: I've added some comments on the code provided, explaining step by step the process.