lisdey89
lisdey89

Reputation: 222

How to render amount selected items with react-select v2

I'm using react-select version 2 and I'm having trouble to change the custom behavior for multi selects. I would like to show the amount of items selected instead of the list of selected items. I mean instead of this: enter image description here

I want this: ![enter image description here

Any help will be really appreciated!

thanks...

Upvotes: 1

Views: 2077

Answers (2)

Laura
Laura

Reputation: 8630

You can use custom components to do something like this:

UPDATE with @lisdey89 open menu behaviour

const ValueContainer = ({ children, ...props }) => {
  const { getValue, hasValue } = props;
  const nbValues = getValue().length;
  if (!hasValue) {
    return (
      <components.ValueContainer {...props}>
        {children}
      </components.ValueContainer>
    );
  }
  return (
    <components.ValueContainer {...props}>
      {`${nbValues} items selected`}
    </components.ValueContainer>
  );
};
const options = [
  { label: "label 1", value: 1 },
  { label: "label 2", value: 2 },
  { label: "label 3", value: 3 },
  { label: "label 4", value: 4 }
];
function App() {
  const components = { ValueContainer };
  return <Select isMulti components={components} options={options} />;
}

Here a live example.

Upvotes: 4

lisdey89
lisdey89

Reputation: 222

After I continue searching based on @Laura's answer I end up with this solution to show the amount of items selected and also maintain the ValueContainer default behavior, maybe someone else could find it useful:

const ValueContainer = ({ children, ...props }) => {
  const { getValue, hasValue } = props;
  const nbValues = getValue().length;
  if (!hasValue) {
    return (
      <components.ValueContainer {...props}>
        {children}
      </components.ValueContainer>
    );
  }
  return (
    <components.ValueContainer {...props}>
      {
        `${nbValues} items selected`
      }
    </components.ValueContainer>
  );
};

Here an example

Upvotes: 1

Related Questions