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

◇◆丶佛笑我妖孽 提交于 2020-01-25 10:14:10

问题


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.


回答1:


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.




回答2:


You can store the value of the first dropdown into the state upon selecting on the first dropdown. And then you base the options of the second dropdown on the state.



来源:https://stackoverflow.com/questions/59692678/reactjs-populate-dropdown-list-based-on-first-dropdown-list-selected-value-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!