Categories
focus javascript react-dom reactjs

How to find focused React component? (like document.activeElement)

If you had 500 components, each with a ref, how would you find which component has the user’s focus? All components with a ref are focusable elements like <input />, <textarea />, etc. For simplicity, all of the refs are accessible from a single top-level component.

This is very simple if your React components have classNames – but if you want to find the ref of a document.activeElement, if there some way to achieve that without having to resort to classNames?

To touch on why we don’t have classNames, we’re using JSS via emotion. To have to manually assign everything a className just for this purpose would be rather absurd. No obvious alternative has occurred to me.