Limit selected options showing in multi-select #4653
-
How to limit selected options showing in multi-select input box and add |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Hello @varora1406, this has already been asked on this repository but for completeness I will offer my own solution. You would have to overwrite the const valueLimit = 3;
const ValueContainer = ({ children, ...props }) => {
const childs = Children.toArray(children);
const valueChildren = childs.filter(child => child.type === components.MultiValue);
const renderableValues = valueChildren.slice(0, valueLimit);
let overflow = valueChildren.length - valueLimit;
return (<components.ValueContainer {...props}>
{renderableValues}
{overflow > 0 && <span>+ {overflow} more</span>}
{childs.filter(child => [components.Input, components.Placeholder].includes(child.type))}
</components.ValueContainer>);
}
<Select isMulti components={{ ValueContainer }} /> |
Beta Was this translation helpful? Give feedback.
-
Personally, I prefer to use the MultiValue index prop to avoid mapping and filtering React.children of the ValueContainer Here is a working codesandbox demo const VALUE_LIMIT = 3;
const MultiValue = (props) => {
const { index, getValue } = props;
const hiddenLength = getValue().length - VALUE_LIMIT;
if (index < VALUE_LIMIT) {
return <components.MultiValue {...props} />
}
if (index === VALUE_LIMIT) {
return <div className="option-label">{`+${hiddenLength} selected`}</div>
}
return null;
};
<Select isMulti components={{ MultiValue }} /> |
Beta Was this translation helpful? Give feedback.
Personally, I prefer to use the MultiValue index prop to avoid mapping and filtering React.children of the ValueContainer
Here is a working codesandbox demo