react-select: Overwrite default styles and remove the clearable 'x' icon

Viewed 7990

Thank you for opening this question. I implemented the react-select.

            <Select
              searchable
              clearable
              name="form-field-name"
              options={options}
              value={this.state.value}
              onChange={this.onChange}
            /> 

When changed the page to RTL, I had some space (padding-right) at the beginning of the selected option. The screenshot attached clarifies that. I tried to add

.has-value.is-clearable.Select--single > .Select-control .Select-value { padding-right: 10px; }

to my own CSS but that didn't work out. please help me fix it.

Another problem, the 'x' that clears the text I couldn't find a way to remove it, the problem is that it neither clears the text nor it could be removed. I used both ways with/without searchable property. Also, it generates an error when clicked because null value returned (I figured that out using console). Please take a look at the following screenshot.

enter image description here

2 Answers

I am not sure about your first question.

To remove 'x' set the isClearable props to false.

<Select
  searchable
  isClearable={false}
  name="form-field-name"
  options={options}
  value={this.state.value}
  onChange={this.onChange}
/> 

The official answer to your first question is to create a custom style and override the native react-select styles like this:

(I think you have to override valueContainer, but I leave you other props you can play with)

const AutocompleteStyles = {
    control: (defaultStyles: any) => ({
      ...defaultStyles,
      padding: '0',
    }),
    option: (defaultStyles: any, state: any) => ({
      ...defaultStyles,
      backgroundColor: 'black',
      '&:hover': {
        backgroundColor: '#dcdcdc4c',
      },
    }),
    singleValue: (defaultStyles: any) => ({
      ...defaultStyles,
      padding: '0',
    }),
    valueContainer: (defaultStyles: any) => {
      return {
        ...defaultStyles,
        padding: '0',
      };
    },
    placeholder: (defaultStyles: any) => {
      return {
        ...defaultStyles,
        padding: '0',
      };
    },
    dropdownIndicator: (defaultStyles: any, state: any) => {
      return {
        ...defaultStyles,
        padding: '0',
      };
    },
    indicatorSeparator: (defaultStyles: any) => {
      return {
        ...defaultStyles,
        display: 'none',
      };
    },
  };

Then, assign those styles to you react-select component like this:

<Select
        ...
        styles={AutocompleteStyles}
      />

As you see, you can receive two props inside the method, first one are the default styles and the second one is the react-select state, in case you would like to handle styles based on component state (Like if you have a selected value or is empty).

For more info, you can check react-select styled component: https://react-select.com/styles

Related