react: Bug: autoFocus broken inside
React version: 17 and 18.0.0-rc.0-next-27b569969-20220211
Steps To Reproduce
- render
<input /><input autoFocus />inside<dialog /> - execute the
showModal()method of the dialog - you will notice that react will not set focus to the correct input element

Link to code example:
https://codesandbox.io/s/dreamy-meninsky-460wbr?file=/src/App.tsx
The current behavior
In Chrome and Safari TP the element with autofocus="true" will receive focus.
However the element with autoFocus={true} will not receive focus.
The expected behavior
From the html-spec https://html.spec.whatwg.org/multipage/interaction.html#the-autofocus-attribute
The autofocus content attribute allows the author to indicate that an element is to be focused […] as soon as the dialog within which it finds itself is shown
From https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/autofocus
The autofocus global attribute is a Boolean attribute indicating that an element should be focused on page load, or when the
<dialog>that it is part of is displayed
Therefore autoFocus={true} should also set the focus similar to autofocus="true" for elements inside <dialog />
About this issue
- Original URL
- State: open
- Created 5 years ago
- Reactions: 38
- Comments: 18 (1 by maintainers)
@jantimon until it’s not fixed you can try this workaround:
bump ++
The issue here is that React takes the
autofocusprop and runs its own logic on it, completely unnecessarily in this case. So the solution for me is to break out of this behavior and set the attribute directly:In order:
reffunction is called, setting the native attributereffunction is called, opening the dialogHello, @Jahb, @Mirijam1, @budihan, and I are a team from TU Delft. We are taking a course called Software Architecture. We chose ReactJS as our project, and would like to start our first contribution with this issue!
Is there any update on this with React19?
Also found the same thing. In a dialog element, if I set the
autoFocusprop on a button like this:It does not work, instead the first focusable element in the dialog receives the autofocus. However, if I set the prop like a normal html prop and use a string
This works properly, although the React compiler/linting breaks here because obviously that’s not how React accepts the prop.
As a workaround, we can use this to manually set the autofocus attribute via DOM APIs.
I’m ok if it takes time to fix, but no one responding to this open ticket is very disappointing.
Another bump 👊