Populate 2nd dropdown based on selection from 1st dropdown in React.Js

前端 未结 3 1131
刺人心
刺人心 2021-02-06 19:11

I am learning react and struggling to get a second dropdown to populate based on which option is clicked from first dropdown.

I have included my code below.

I

3条回答
  •  迷失自我
    2021-02-06 19:53

    You're doing it wrong way. You cannot call onClick method on . Instead you should use onChange method on

    Then on 'onChange' event you can set your state to the selected option. Let's understand this scenario with an example.

    Suppose you have two dropdowns. One for showing companies and one for jobs corresponding to each company. Each company has its own set of jobs like this:

     companies:[
        { name: 'company1',  jobs: ['job1-1', 'job1-2', 'job1-3']},
        { name: 'company2', jobs: ['job2-1', 'job2-2', 'job2-3']},
        { name: 'company3', jobs: ['job3-1', 'job3-2', 'job3-3']}
      ]
    

    Now you have to just set a state, lets say 'selectedCompany' and then filter the companies array by 'selectedCompany'. Then you can just get that particular company object and map your 'jobs' dropdown by iterating over jobs array inside the company object.

    Here is the code snippet: https://codepen.io/madhurgarg71/pen/pRpoMw

提交回复
热议问题