How to change a select’s options based on another dropdown using React?
Select in HTML allows us to choose among multiple values using the dropdown. Here, we are talking about changing select options based on another dropdown. In React, it is very easy to achieve with the help of the state. For those who don’t about state here is a brief of it.
The STATE of a component is an object that holds some information that may change over the lifetime of the component.
React has both Class-Based components and Functional Component so for this article, we will use Functional Component. In the Functional component, the state can be managed using useState hook.
We want to change the selects options based on other dropdowns so we will follow the below steps.
- Create a state variable that is initially null or undefined.
- Create different arrays for different dropdowns.
- Create a local variable say type that will hold any of the array based on the dropdown selected.
- Create a function that will be called whenever an option from the dropdown is selected, this function will change the state variable so that the value of type can be determined dynamically.
- Lastly, use type variables to create a different set of options that the user will see.
Now we will create a Component using all the steps described above.
App.js: Below is the code for App.js component.
Note: You can also use the Class-Based component, logic would be the same.