How to change a select’s options based on another dropdown using React?
Last Updated :
18 Nov, 2020
React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front end library responsible only for the view layer of the application. It is maintained by Facebook.
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.
If you want to know more about the state, please refer to state in react geeksforgeeks and state and lifecycle reactjs.org.
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.
Javascript
import * as React from "react" ;
const App = () => {
const [selected, setSelected] = React.useState( "" );
const changeSelectOptionHandler = (event) => {
setSelected(event.target.value);
};
const algorithm = [
"Searching Algorithm" ,
"Sorting Algorithm" ,
"Graph Algorithm" ,
];
const language = [ "C++" , "Java" , "Python" , "C#" ];
const dataStructure = [ "Arrays" , "LinkedList" , "Stack" , "Queue" ];
let type = null ;
let options = null ;
if (selected === "Algorithm" ) {
type = algorithm;
} else if (selected === "Language" ) {
type = language;
} else if (selected === "Data Structure" ) {
type = dataStructure;
}
if (type) {
options = type.map((el) => <option key={el}>{el}</option>);
}
return (
<div
style={{
padding: "16px" ,
margin: "16px" ,
}}
>
<form>
<div>
{
}
<select onChange={changeSelectOptionHandler}>
<option>Choose...</option>
<option>Algorithm</option>
<option>Language</option>
<option>Data Structure</option>
</select>
</div>
<div>
<select>
{
options
}
</select>
</div>
</form>
</div>
);
};
export default App;
|
Output:
Note: You can also use the Class-Based component, logic would be the same.
Share your thoughts in the comments
Please Login to comment...