Repository navigation
MenuButton ref not working in React 19 #3706
|
What package within Headless UI are you using? @headlessui/react What version of that package are you using? v2.2.2 What browser are you using? For example: Chrome Describe your issue I'm trying to open a Menu programatically by passing a ref to MenuButton and calling function MyComponent() {
const menuButtonRef = useRef(null);
// Open the menu with the cmd-K shortcut
useEffect(() => {
const onKeydown = (e: KeyboardEvent) => {
if ((e.key === 'k' || e.key === 'K') && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
console.log('cmd-K'); // This logs as expected
menuButtonRef.current?.click(); // This does nothing
}
};
document.addEventListener('keydown', onKeydown);
return () => document.removeEventListener('keydown', onKeydown);
}, []);
return(
<Menu>
<MenuButton ref={menuButtonRef}>
Button
</MenuButton>
<MenuItems anchor={{ to: 'bottom start', gap: 4 }} modal={false}>
...
</MenuItems>
</Menu>
} |
Replies: 2 comments
|
@RobinMalfait Any updates on this? And why has it been moved to a discussion when this is a regression? |
|
I dug into export function useHandleToggle(cb) {
const pointerTypeRef = useRef<'touch' | 'mouse' | 'pen' | null>(null);
const handlePointerDown = useEvent((event) => {
pointerTypeRef.current = event.pointerType;
if (event.pointerType !== 'mouse') return;
// ...
cb(event);
});
const handleClick = useEvent((event) => {
if (pointerTypeRef.current === 'mouse') return; // <-- this
// ...
cb(event);
});
return { onPointerDown: handlePointerDown, onClick: handleClick };
}The toggle logic for a real mouse click actually runs on The problem is Workaround that works today, force menuButtonRef.current?.dispatchEvent(
new PointerEvent('pointerdown', { pointerType: 'touch', bubbles: true })
);
menuButtonRef.current?.click();The first line gets swallowed by |
I dug into
packages/@headlessui-react/src/hooks/use-handle-toggle.tsx, which is whatMenuButtonactually wires up instead of a plainonClick:The toggle logic for a real mouse click actually runs…