Adding a select dropdown in React is quite straightforward.
There are multiple ways do is but let’s go through one way of enabling multi select options.
Let’s try to change the same React select dropdown example and make it accept multiple options value.
The first and foremost thing we need to do is change the select element and make it let use select multiple values.
...
...
...
...
The second thing we need to change is the constructor method and add an array so that we can use that array to store multiple selections from the user.
...
this.state = {
options: ["React"],
};
...
After that, we need to change the handleChange method to make it handle the multiple options data.
...
handleChange(event) {
let value = Array.from(
event.target.selectedOptions,
(option) => option.value
);
this.setState({
options: value,
});
}
...
If you’ve a submit button then you need to change the handleSubmit method as well to handle the submitted data.
I have added just an alert to show submitted data to users but it’s up to you how you want to handle the submitted data.
Also, I am using slice method to remove the trailing comma and space since I am appending the strings in for loop.
...
handleSubmit(event) {
let alertTexts = "";
for (var i = 0; i < this.state.options.length; i++) {
alertTexts += this.state.options[i] + ", ";
}
alertTexts = alertTexts.slice(0, -2); //remove the trailing space and comma
alert("You selected " + alertTexts);
event.preventDefault();
}
...
Example
I have not added any style to it but you can always use CSS to make it look better.
constructor drop down examples select values