I am using react select control in my ReactJs based application. I am using this as a multi-select control. But once the user selects more than 1 value, instead of showing all the selected values, I want to show the first selected value + N. So if two values are selected, I want to say 'XYZ' + 1. If only one value is selected I will say 'XYZ'. here is a working example
1 Answer
You need to override ValueContainer like below. working sandbox
const ValueContainer = props => {
let length = props.getValue().length;
return (
<components.ValueContainer {...props}>
{length > 1 ? (
<>
{props.children[0][0]}
{!props.selectProps.menuIsOpen && `${length - 1} Items`}
{React.cloneElement(props.children[1])}
</>
) : (
<>{props.children}</>
)}
</components.ValueContainer>
);
};
In Select you need to override
<Select
components={{ValueContainer}}
hideSelectedOptions={false}
...
/>
3 Comments
SharpCoder
Upvoting as solution works. But now, how do we remove some of the selected values?
gautamits
You can avoid hiding selected values, so that selected values are available in dropdown for unselecting. ``` <Select components={{ValueContainer}} hideSelectedOptions={false} ... /> ``` Updated sandbox also.
SharpCoder
Can you please explain what is happening inside
ValueContainer
+ N? Is it something like if a user selects option 1, then also selects option 3, that you display options 1, 2, and 3? or if they also select option 3 you just display option 1 and 2? You're expected result could use a bit more detail.Option 1, since this the only item selected, we will show Option 1 as the selected value. now if user selectsOption 3, we will showOption 1 + 1as we have two selected items in control. if user selectsOption 6, we will showOption 1 + 2as we have three selected items in control.