Shah Lav
Shah Lav

Reputation: 143

How to remove selected symbol from react-select input?

I am using a react-select and used formatOptionLabel prop to format the options label. Whenever I select any option it is shown in Input and it is also getting that formatted label

I tried passing selectedIcon and removed it on onChange event and that did work, But for that I need to pass it in each option and remove on each onChange.

This is the handleValueChange

handleChange = (value) => {
    const { selectedIcon, ...restFields } = value;
    this.setState({
      someKey: restFields
    });
};

This is the formatLabel function I have used

const formatLabel = (data, restFields) => {
  if (restFields.selectValue[0].value === data.value) {
    return (
      <div>
        {data.selectedIcon}{data.icon}{data.label}
      </div>
    )
  } else {
    return (
      <div>
        {data.icon}{data.label}
      </div>
    )
  }
};

Is there a way to format selected value differently when menu is not open. and also I need to apply different styles to both of them.

For example: I want to show ✔️ inside options menu before selected values and when menu is close it should only show the selected value.

Upvotes: 1

Views: 4750

Answers (1)

user6612182
user6612182

Reputation:

For styling you can use the styling api to style each of the components individually. It provides the initial styles (in docs as provided) and the provided props (in docs as state) as arguments and returns a styles object.

<Select
    { ... }
    styles={{
        option: (provided, state) => ({
            ...provided,
            // Your styles here
        }),
        singleValue: (provided, state) => ({
            ...provided,
            // Your styles here
        })
    }}
/>

If you just want to render a check mark on a selected option you could do it with the styling api and pseudo elements.

{
    ...provided,
    '&:before': {
        fontFamily: "FontAwesome" // For example
        content: "\f00c"
    }
}

Another method would be to use the components framework to overwrite Option and/or SingleValue (or MultiValue) components (both use the result of formatOptionLabelas their immediate React child).

const Option = ({ children, ...props }) => <components.Option { ...props }>
    {/* I'll do it my way */}
    { customLabelFormat(props.data) }
    {/* Or like this as per your request */}
    { props.isSelected && <CheckMark /> }
    { children } // To keep default label format as an example
</components.Option>;

<Select
    { ... }
    components={{
        Option
    }}
/>

Upvotes: 2

Related Questions