Skip to content

useFocus

Opens the floating element while the reference element has focus, like CSS :focus.

import {useFocus} from '@floating-ui/react';
import {useFocus} from '@floating-ui/react';

Usage

This hook is an interaction hook that returns event handler props.

To use it, pass it the contextcontext object returned from useFloating()useFloating(), and then feed its result into the useInteractions()useInteractions() array. The returned prop getters are then spread onto the elements for rendering.

function App() {
  const [isOpen, setIsOpen] = useState(false);
 
  const {refs, floatingStyles, context} = useFloating({
    open: isOpen,
    onOpenChange: setIsOpen,
  });
 
  const focus = useFocus(context);
 
  const {getReferenceProps, getFloatingProps} = useInteractions([
    focus,
  ]);
 
  return (
    <>
      <div ref={refs.setReference} {...getReferenceProps()}>
        Reference element
      </div>
      {isOpen && (
        <div
          ref={refs.setFloating}
          style={floatingStyles}
          {...getFloatingProps()}
        >
          Floating element
        </div>
      )}
    </>
  );
}
function App() {
  const [isOpen, setIsOpen] = useState(false);
 
  const {refs, floatingStyles, context} = useFloating({
    open: isOpen,
    onOpenChange: setIsOpen,
  });
 
  const focus = useFocus(context);
 
  const {getReferenceProps, getFloatingProps} = useInteractions([
    focus,
  ]);
 
  return (
    <>
      <div ref={refs.setReference} {...getReferenceProps()}>
        Reference element
      </div>
      {isOpen && (
        <div
          ref={refs.setFloating}
          style={floatingStyles}
          {...getFloatingProps()}
        >
          Floating element
        </div>
      )}
    </>
  );
}

Props

interface Props {
  enabled?: boolean;
  keyboardOnly?: boolean;
}
interface Props {
  enabled?: boolean;
  keyboardOnly?: boolean;
}

enabled

default: truetrue

Conditionally enable/disable the hook.

useFocus(context, {
  enabled: false,
});
useFocus(context, {
  enabled: false,
});

keyboardOnly

default: truetrue

Whether the state only changes if the focusfocus event was triggered via keyboard rather than any pointer inputs (mouse/touch/pen). Programmatic .focus().focus() calls are considered as keyboard.

useFocus(context, {
  keyboardOnly: false,
});
useFocus(context, {
  keyboardOnly: false,
});