javascriptreactjspopoverautofocusfloating-ui

Autofocus of input inside a popover makes the page scroll


When I have a popover inside a scrollable area with any floating lib in react (tippy, floating-ui, etcetc), and I have an input with autoFocus inside the popover, the screen will scroll when the popover renders. How do I get around this?


Solution

  • Libraries like floating-ui or tippy position the element after it has been mounted. The popover will therefore position itself at for example x: 0, y: 0 for a short period, and autoFocus automatically scrolls the page for the popover to fit in the viewport. This can be resolved by turning of autoFocus and instead calling inputRef.current.focus({preventScroll: true}) right after the component has mounted

    There are hackier ways like setting the focus on a setTimeout but that makes it more complex.