Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop react-select from expanding as options are added

So I am looking into potentially using react-select for a project that requires multi-select. However, the multi-select example keeps expanding down as more items are selected. This won't work if a dropdown has a bunch of options to choose from (lets say 100). Is there a way within the react-select library to have the value be "Xyz & 5 more" or something similar?

import React, { Component } from 'react'
import Select from 'react-select'

const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' },
  { value: 'cherry', label: 'Cherry' },
  { value: 'foo', label: 'Foo' },
  { value: 'bar', label: 'Bar' }
]

const MyComponent = () => (
  <Select
    options={options}
    isMulti
    className="basic-multi-select"
    classNamePrefix="select"
  />
)
like image 760
James Robert Singleton Avatar asked Nov 02 '25 12:11

James Robert Singleton


1 Answers

You can use the components framework to overwrite the ValueContainer component which holds the selected values in their badge form.

const ValueContainer = ({ children, getValue, ...props }) => {
  var values = getValue();
  var valueLabel = "";

  if (values.length > 0) valueLabel += props.selectProps.getOptionLabel(values[0]);
  if (values.length > 1) valueLabel += ` & ${values.length - 1} more`;

  // Keep standard placeholder and input from react-select
  var childsToRender = React.Children.toArray(children).filter((child) => ['Input', 'DummyInput', 'Placeholder'].indexOf(child.type.name) >= 0);

  return (
    <components.ValueContainer {...props}>
      {!props.selectProps.inputValue && valueLabel }
      { childsToRender }
    </components.ValueContainer>
  );
};

<Select
  { ... }
  isMulti
  components={{
    ValueContainer
  }}
  hideSelectedOptions={false}
/>

Notice the filtering and inclusion of the Input (or DummyInput) component: Without it basic functionality of the Select component (like focus, etc.) will be lost. Also set hideSelectedOptions prop to false so you can deselect selected options.

A functioning example can be viewed here.