tailwindlabs / headlessui

Completely unstyled, fully accessible UI components, designed to integrate beautifully with Tailwind CSS.
https://headlessui.com
MIT License
25.02k stars 1.03k forks source link

Dialog text input React DOM ref not initialized soon enough #3341

Closed forresttanaka closed 4 days ago

forresttanaka commented 5 days ago

What package within Headless UI are you using? @headlessui/react Dialog

What version of that package are you using? v2.1.1

What browser are you using? Edge 126.0.2592.61, Safari 17.5

Reproduction URL https://codesandbox.io/p/sandbox/headlessui-dialog-ref-bug-m49wwn?file=%2Fsrc%2FApp.js%3A22%2C15

Describe your issue I want to focus a text input as soon as the dialog opens so that the user can immediately start typing their search term. To do this, I have a useEffect with the boolean isOpen as its dependency. I pass this boolean to the open attribute to <Dialog>. useEffect clears the text input, then uses the <input type="text" ref={inputRef} /> ref to focus using inputRef.current.focus();.

With @headlessui/react 2.0.4 this worked correctly. With 2.1.1 I get a crash on this focus line because inputRef.current still contains null. I don’t see inputRef.current get a value until the user clicks the text input field and starts typing. At this stage, I don’t know how to focus on the text input as soon as the dialog opens with 2.1.1.

RobinMalfait commented 4 days ago

Hey! You can add the data-autofocus attribute to the input. More info: https://headlessui.com/react/dialog#managing-initial-focus

forresttanaka commented 4 days ago

You can add the data-autofocus attribute to the input

Completely missed that. Thank you!