I am using the Headless UI Combobox as an autocomplete search bar (React/Remix app). I would like the search bar to give up focus after the search is submitted.
On some devices (e.g. iPhone Safari) it seems to do this by default; however, on desktop Chrome I get very different behavior. The combobox refocuses and I cant figure out when/why it is doing this, so I can't manually blur it in a useEffect.
All I could do to hack it was blur the bar on a setTimeout.
I encountered a similar issue and found a solution that may not be the most elegant but it does the job.
First, I added a ref to the ComboBox input element and used a setTimeout with a delay of 0 to blur it:
const handleChange = (event) => {
// other stuff
setTimeout(() => {
searchRef.current.blur()
}, 0)
}
// a structure like this
<ComboBox onChange={handleChange}>
<Combobox.Input ref={searchRef} />
</ComboBox>
This worked fine for keyboard input, but I noticed that when I clicked on the ComboBox, it would immediately focus and then blur due to the setTimeout, creating a noticeable blinking effect. To fix this, I added an onMouseDown event to the ComboBox and called preventDefault() to prevent the input from being focused:
<Combobox.Options
onMouseDown={(e) => {
e.preventDefault()
}}
/>
Like you said it's kinda hacky but it works and after working on it for several hours, it working is better than it not working plus I don't get paid so no one will look at the code anyway.