How to blur the select after a clear is executed? #5964
Unanswered
Rafael-Ramblas
asked this question in
Q&A
Replies: 1 comment
-
Hi @Rafael-Ramblas, hope this comment by @ebonow helps: #1309 (comment). Codesandbox Link:Screenshot:Code:import { useRef, useState } from "react";
import Select, {
SelectInstance,
OnChangeValue,
ActionMeta,
} from "react-select";
import "./styles.css";
interface ColorOption {
value: string;
label: string;
}
const colorOptions: ColorOption[] = [
{ value: "red", label: "Red" },
{ value: "green", label: "Green" },
{ value: "blue", label: "Blue" },
];
const SelectComponent: React.FC = () => {
const [value, setValue] = useState();
const selectRef = useRef<SelectInstance<ColorOption> | null>(null);
function onClear() {
setTimeout(() => selectRef?.current?.blur(), 1);
}
const handleChange = (
newValue: OnChangeValue<ColorOption, boolean>,
actionMeta: ActionMeta<ColorOption>
) => {
if (actionMeta.action === "clear") {
onClear();
}
setValue(newValue);
};
return (
<div>
<Select
ref={selectRef}
options={colorOptions}
onChange={handleChange}
value={value}
isClearable
onBlur={() => console.warn("blur")}
onFocus={() => console.warn("focus")}
/>
</div>
);
};
export default function App() {
return <SelectComponent />;
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hey everyone!
I’m working with react-select in my project and I want to prevent the Select component from gaining focus after clearing the value. Using the actionMeta prop with the select ref is not working because the select is focused again after the blur.
Here’s what I have so far:
https://codesandbox.io/p/sandbox/82rkp7
As you can see, right after the
onBlur
is executed, theonFocus
is executed too, so I don't know if there's a racing condition happening or some event propagation that I'm not aware of.One workaround that I found was to put the
selectRef?.current?.blur()
call inside a setTimeout function.Any tips or suggestions would be awesome! Thanks in advance!
Beta Was this translation helpful? Give feedback.
All reactions