Handling Multiple Select in React

In React, when working with a select element that supports multiple selections (using the multiple attribute), it’s important to properly retrieve and manage the selected values. While React allows you to control the selected options via the value prop (using an array), the onChange event does not return the selected values directly in array form. Instead, you must manually extract them from the event.

Why Manual Extraction Is Necessary:

The e.target.options property returns an HTMLOptionsCollection, which contains allelements inside the select tag. To obtain only the selected options:

  1. Convert the collection into an array using Array.from().
  2. Filter to keep only selected options.
  3. Map the selected options to their respective values.

This approach ensures accurate retrieval and alignment with React’s controlled component model.

Class Component Example

var MultiSelectComponent = React.createClass({
  handleChange: function(e) {
    const selectedValues = Array.from(e.target.options)
      .filter(option => option.selected)
      .map(option => option.value);

    this.props.someCallbackFromParent(selectedValues);
  },

  render: function() {
    return (
      <select multiple={true} value={this.props.arrayOfOptionValues} onChange={this.handleChange}>
        <option value="1">First option</option>
        <option value="2">Second option</option>
        <option value="3">Third option</option>
      </select>
    );
  }
});

Functional Component (Modern React with Hooks)

import React from 'react';

const MultiSelectComponent = ({ arrayOfOptionValues, someCallbackFromParent }) => {
  const handleChange = (e) => {
    const selectedValues = Array.from(e.target.options)
      .filter(option => option.selected)
      .map(option => option.value); // or parseInt(option.value, 10) if numeric

    someCallbackFromParent(selectedValues);
  };

  return (
    
  );
};

Key Notes:

  • The .value of an option tag element is always returned as a string. If you expect numeric values, convert them using parseInt(option.value, 10) or Number(option.value) to ensure type consistency.
  • This technique aligns with React’s controlled form approach and ensures that selected values are accurately captured and passed to the parent component for further handling (e.g., via state updates).

Using this pattern, you can build reliable multi-select inputs in both class-based and functional React components.

Need Help With React Development?

Work with our skilled React developers to accelerate your project and boost its performance.

Hire Reactjs Developers

Support On Demand!

Related Q&A