Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set max number of items that can be selected in react-select?

I am using CreatableSelect component from react-select. Now users can select as many items as they want, but I want users to select no more than 5 items. How to limit max number of options that can be selected?

<CreatableSelect
  classes={classes}
  styles={selectStyles}
  textFieldProps={{
    label: "Tags"
  }}
  options={suggestions}
  components={components}
  value={this.state.multi}
  onChange={this.handleChange("multi")}
  placeholder=""
  isMulti
/>
like image 349
Bositkhon Sultonov Avatar asked Mar 12 '19 10:03

Bositkhon Sultonov


People also ask

How set selected value of select in React?

To set selected value of a select drop down to null with React, we can set the state we use as the value of the value prop of the select drop down to null . to set onChange to a function that calls setSelected to e. target. value which is the selected value if it's truthy.

How set multiple values in React select?

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.


Video Answer


2 Answers

I recommend you to use a combination of custom component Menu and isValidNewOption like the following code:

// For this example the limite will be 5
    const Menu = props => {
      const optionSelectedLength = props.getValue().length || 0;
      return (
        <components.Menu {...props}>
          {optionSelectedLength < 5 ? (
            props.children
          ) : (
            <div>Max limit achieved</div>
          )}
        </components.Menu>
      );
    };

    function App() {
      const isValidNewOption = (inputValue, selectValue) =>
        inputValue.length > 0 && selectValue.length < 5;
      return (
        <div className="App">
          <Creatable
            components={{ Menu }}
            isMulti
            isValidNewOption={isValidNewOption}
            options={options}
          />
        </div>
      );
    }

Here a live example.

The idea is to prevent user to access the options after the limit X (5 in the example) and also to prevent the enter keyboard event on create through isValidNewOption prop.

like image 108
Laura Avatar answered Oct 31 '22 10:10

Laura


a very easy way to do this is:

<Select
        value={tags}
        onChange={(v) => v.length < 4 ? setTags(v): null}
        isMulti
        name='tags'
        options={options}
        className='basic-multi-select'
        classNamePrefix='select'
      />

just add a simple ternary check for how many items you wants

like image 26
Methkal Khalawi Avatar answered Oct 31 '22 10:10

Methkal Khalawi