react-select - Show different text/label for drop-

2019-07-19 12:12发布

In my react-select drop-down, the labels are hundreds of characters long. In the Control chips, I would like to show a shorter version of what's in the drop-down. Is this possible?

Edit: I want to set the text of the chip, not pixel width.

1条回答
我命由我不由天
2楼-- · 2019-07-19 12:53

SOLUTION 1

You can custom the style of the control chips when using the multiple value Select with the props styles like the following example:

const customStyles = {

    multiValue: (base, state) => ({
      ...base,
     // set all chips to a maximum of 100 pixels
      maxWidth: "100px"
    })
  };

Here a live example of shorter versions of long label. I put special (and ugly) background so you can see where each container starts and ends.

SOLUTION 2

Following the comment request this is an alternative solution to cut the selected option. You can overwrite the component MultiValue with the prop components. Inside this component you will have access to the option label and apply substring function to truncate the label as short as you can.

const MultiValue = props => {
// truncate the string to 3 characters
   const content = props.children.substring(0, 3);
   return <components.MultiValue {...props}>{content}...</components.MultiValue>;
};

Here a live example of this alternative option.

SOLUTION 3

In the same idea as the solution 2 if you know in advance your option labels and the crop you want to display you can set an extra props in your options array like this:

const options = [
  {
    label:
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi augue sem, bibendum quis mollis amet.",
    // you can name this new prop has you want
    chipLabel: "Lorem ipsum",
    value: "1"
  },
  {
    label:
      "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium.",
    chipLabel: "Sed ut perspiciatis",
    value: "2"
  },
  {
    label:
      "Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?",
    chipLabel: "Ut enim",
    value: "3"
  }
];

And then overwrite the component with the following code:

const MultiValue = props => (
  <components.MultiValue {...props}>
    {props.data.chipLabel}
  </components.MultiValue>
);

<Select options={options} components={{ MultiValue }} />

Here a live example.

SOLUTION FOR SINGLE VALUE

If you want to display a different value than in options for SingleValue select I recommend to use the solution 3 and change the component like this:

const SingleValue = props => (
  <components.SingleValue {...props}>
    {props.data.chipLabel}
  </components.SingleValue>
);

<Select options={options} components={{ SingleValue }} />

Here a live example.

查看更多
登录 后发表回答