Closed forresttanaka closed 4 days ago
Hey! You can add the data-autofocus
attribute to the input. More info: https://headlessui.com/react/dialog#managing-initial-focus
You can add the data-autofocus attribute to the input
Completely missed that. Thank you!
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 theopen
attribute to<Dialog>
. useEffect clears the text input, then uses the<input type="text" ref={inputRef} />
ref to focus usinginputRef.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 seeinputRef.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.