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
I have edited your code and moved the actions taken on the select itself directly in the default component (where select is located):
Also, remove
onClick
from theClearIndicator
element:Tip:
Never
useState
to store a reference to an element. UseuseRef
- find more here