How to set max number of items that can be selected in react-select?
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