1

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

3
  • How do you determine + 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. Commented Jun 5, 2020 at 5:05
  • React-select will only display the labels that are available in the array that you provide. Commented Jun 5, 2020 at 5:12
  • @DrewReese:If user select Option 1, since this the only item selected, we will show Option 1 as the selected value. now if user selects Option 3, we will show Option 1 + 1 as we have two selected items in control. if user selects Option 6, we will show Option 1 + 2 as we have three selected items in control. Commented Jun 5, 2020 at 5:13

1 Answer 1

1

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}
 ...
/>
Sign up to request clarification or add additional context in comments.

3 Comments

Upvoting as solution works. But now, how do we remove some of the selected values?
You can avoid hiding selected values, so that selected values are available in dropdown for unselecting. ``` <Select components={{ValueContainer}} hideSelectedOptions={false} ... /> ``` Updated sandbox also.
Can you please explain what is happening inside ValueContainer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.