简体   繁体   中英

Best way to add a prefix to a react-select box

I'm working with react-select and was wondering how I can get the component to prefix the selected label with Show: or any other copy I'd like? I'd prefer to bake this into the component rather than change the labels. Hopefully this is possible.

Bonus question: how can I easily remove the left border line on the DropdownIndicator . It doesn't seem to be apart of the indicator at all.

在此处输入图像描述

You can override every sub-components of Select to change the behavior of the components. In your case, prefix the selected value with whatever you want. Here's a small example to get your started.

If you want to remove the IndicatorSeparator component, simply create a corresponding component that returns null

const VALUE_PREFIX = "Show: ";

export default function MySelect() {
  return (
    <Select
      options={options}
      placeholder="All"
      components={{
        SingleValue: ({ children, ...props }) => {
          return (
            <components.SingleValue {...props}>
              {VALUE_PREFIX + children}
            </components.SingleValue>
          );
        },
        Placeholder: ({ children, ...props }) => {
          return (
            <components.Placeholder {...props}>
              {VALUE_PREFIX + children}
            </components.Placeholder>
          );
        },
        IndicatorSeparator: () => null,
      }}
    />
  );
}

Live Demo

编辑 64014975/best-way-to-add-a-prefix-to-a-react-select-box

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM