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
/>
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With