Three ways to autofocus in React (that almost always work) | Daniel Johnson

Whilst accessibility means you largely want to steer clear of autofocus on web forms, sometimes it can be beneficial. In HTML, we can now reach for the handy autofocus attribute, but as I recently learnt that doesn't always do what you expect when dealing with a shadow DOM (in this case, React's equivalent). Daniel's article was by far the best at both describing the issue and offering some solutions, though even here it only works most of the time (Firefox does something which I feel is logical but unfortunately not consistent with either the W3C spec or what most people would want to happen).

So here are the (confusingly more than three) techniques:

  • The autofocus attribute (😉) for input elements that are always present (elements loaded later have some weird cross-browser differences);
  • The focus() DOM API that allows you to select an element using JavaScript and force focus on it i.e. element.focus(), which works almost always but can be tricky to target correctly (and reliant on client-side JavaScript);
    • FYI remember that the opposite of focus() is blur(), and both can be handily combo'd with select() for some even better UX!
  • The React autoFocus prop, which effectively mimics the HTML autofocus attribute but only triggers it when a component mounts, helping with the cross-browser issues but meaning that if you mount before visually showing an element it can steal focus incorrectly;
  • The useRef hook, which is effectively just using the focus() API within React's own life cycle;
  • The useCallback hook, which does the same thing as useRef only with more control. This appears to be the most universal option in React right now.

Explore Other Notes

Newer

The markup de-crapulator

A humorous but useful tool that strips out all the mess that things like Styled Components and React make out of HTML and lets you properly view the source of a page. (and yeah, I use those same …

Older

Firefox and SVG fill for CSS

I ran into a bug recently where some SVGs on a website were seemingly ignoring a fill request. A quick check in dev tools showed that the CSS was being applied so... what gives? Turns out …

  • <!DOCTYPE html> <html> <head> <title></title> </head> <body> <p>Whilst accessibility means you largely want to steer clear of autofocus on web forms, sometimes it can be beneficial. In HTML, we can now reach for the handy autofocus attribute, but as I recently …</p> </body> </html>
  • Murray Adcock.
Journal permalink