immediate prop on Combobox and autoFocus on ComboboxInput - options won't open
What package within Headless UI are you using? @headlessui/react
What version of that package are you using?
v2.2.0
What browser are you using? Chrome
Reproduction URL https://codesandbox.io/p/sandbox/headlessui-react-df56c2 Just keep clicking no refresh you will see the input is focused but the options won't open
Describe your issue When setting the immediate prop on Combobox and autoFocus on ComboboxInput, the input gets the focus by default but the options won't automatically open.
I think I'm also experiencing this issue.
We're seeing the same problem in our app. When placed in a dialog, and the combobox has auto-focus, the menu is not displayed even though immediate is on. Clicking or otherwise focusing the combobox will make the menu appear.
Same happens in vue, the immediate prop doesn't seem to be propagated down to the ComboboxInput component:
https://github.com/user-attachments/assets/3551db95-5a4b-46c7-b8e9-2673accb6c21
To overcome this I had to artificially "click" on the ComoboxButton when the input gets focus.
@RobinMalfait bringing this to your attention as there are multiple reports of the same bug across vue and react.
Hey!
Internally we have an onFocus on the input element, when we receive focus and the immediate prop is used then we open the Combobox and that's about it.
The problem is that autoFocus prop is a little weird because it will focus the element on the initial mount, but if your component re-renders it for some reason skips it (onFocus is not always called). But the example in CodeSandbox renders at least 2 times (for some reason), see: https://codesandbox.io/p/sandbox/headlessui-react-df56c2
If you truly only render once, then it works as expected:
https://github.com/user-attachments/assets/19b3ee4a-3684-4620-a272-cffde0cb7192
Now that said in a real app, it is not uncommon that an app re-renders multiple times (even "initially"). The CodeSandbox link above is one example where that's the case.
So I would recommend to use the ref instead of the autoFocus prop as a workaround:
<ComboboxInput
- autoFocus
+ ref={(e) => e?.focus()}
At least in my testing this works every time. Maybe we can intercept the autoFocus prop and do this ourselves internally but then there would be situations where the onFocus is called twice. For our internal implementation that's not an issue because opening the Combobox is idempotent, but if your own code has an onFocus then you might see 2 events...
Going to close this for now, but might improve this in the future ourselves.
Hope this helps!