YogeshChauhan . com

How to select multiple values in React dropdown?

in React on May 16, 2021

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.



...
...
  <select
    multiple={true}
    value={this.state.options}
    onChange={this.handleChange}
  >
    <option value="React">React</option>
    <option value="Angular">Angular</option>
    <option value="Vue">Vue</option>
  </select>
...
...


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.

amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

List of all Pseudo Elements in CSSCSSHow to add Lifecycle Methods to a Class in React?ReactALTER DATABASE in PostgreSQLPostgresWhat’s the difference between variables in CSS and SCSS (Sass)?CSSConfiguring Modules with @forward rule in SCSS (Sass)SCSSLearn to Make a Simple Contact Us Form using PHP and PDO-MySQLPHP