How to override ClearIndicator's onClick to blur control on clear in react-select?

1.8k Views Asked by At

I want to blur (remove focus from) the control field in react-select soon as the ClearIndicator button is clicked.

I tried using a custom ClearIndicator component and defining an onClick handler for it but that doesn't seem to affect the onClick behaviour of the clear button.

Is there a way I can override or modify the onClick behaviour of the ClearIndicator button so I can call the blur() method when the Clear button gets clicked?

The code I tried is given below.

// react-select main component

<Select
  components={{ ClearIndicator }}
  isSearchable
  isClearable
 />
// custom clear button

export const ClearIndicator = (props: any) => {
  const {
    children = <>clear</>,
    getStyles,
    innerProps: { ref, ...restInnerProps },
  } = props;

  const handleClearValue = () => {
    ref.blur();
  };

  return (
    <div
      {...restInnerProps}
      ref={ref}
      style={getStyles("clearIndicator", props)}
      onClick={handleClearValue}
    >
      <div style={{ padding: "0px 5px" }}>{children}</div>
    </div>
  );
};

Codesandbox link: https://codesandbox.io/s/solitary-voice-0qmvc?file=/example.jsx

1

There are 1 best solutions below

1
On

I have edited your code and moved the actions taken on the select itself directly in the default component (where select is located):

export default () => {
  
  const selectRef = useRef(null);
  const blurOut = () => {
    selectRef.current.blur();
  }
  return (
    <Select
      ref={selectRef}
      onChange={blurOut}
      defaultValue={colourOptions[1]}
      options={colourOptions}
      components={ClearIndicator }
      isClearable
    />
  );
};

Also, remove onClick from the ClearIndicator element:

const ClearIndicator = (props) => {
  const {
    children = <CustomClearText />,
    getStyles,
    innerProps: { ref, ...restInnerProps }
  } = props;


  return (
    <div
      {...restInnerProps}
      ref={ref}
      style={getStyles("clearIndicator", props)}
      
    >
      <div style={{ padding: "0px 5px" }}>{children}</div>
    </div>
  );
};

Tip:

Never useState to store a reference to an element. Use useRef - find more here