Recently, on stream, I needed to focus an element. It wasn't focusing until I kicked the focus to the next iteration of the event loop. There are a fe

Code Locality Concerns | Chris Griffing

submited by
Style Pass
2024-04-16 02:30:02

Recently, on stream, I needed to focus an element. It wasn't focusing until I kicked the focus to the next iteration of the event loop. There are a few ways to do such a thing and it brought up a concern I had about code locality vs being idiomatic.

I have a search button on the marketing and documentation site for Vexilla at https://vexilla.dev. After a recent co-stream with GrahamTheDev and Todd Libby, I discovered that there was a focus issue with my "Search" functionality. When a user tabs to the button and activates, they can search using Pagefind. If they close the modal, it should refocus the button that they used to show the modal.

It turns out that this was not as simple as it should have been. I made a useRef and attached it to the button. The ref itself was resolving to the HTML element as expected, but the focus() wasn't actually focusing the button.

First, we made sure that the element could be focused via dev tools and focus(). Yup. Worked as expected. So it wasn't just an issue of the button not being the right ref.

Leave a Comment