Skip to main content

Trap Focus

Trap Focus is a utility that moves screen reader focus between overlay layers, such as a dialog and its opening control.

Import

import { TrapFocus } from '@vortexlabs/vortex-native';
import { type FocusTarget, TrapFocus } from "@vortexlabs/vortex-native";
import { useEffect, useRef, useState } from "react";
import { type HostInstance, Text, View } from "react-native";

type Props = {
  returnFocusRef: FocusTarget;
};

export const TicketPanel = (props: Props) => {
  const { returnFocusRef } = props;
  const root = useRef<HostInstance>(null);
  const [focus] = useState(() => new TrapFocus());

  useEffect(() => {
    focus.trap(root, { returnFocusRef });
    return () => focus.release();
  }, [focus, returnFocusRef]);

  return (
    <View ref={root} accessible accessibilityViewIsModal>
      <Text>Boarding pass</Text>
    </View>
  );
};

Features

  • Moves screen reader focus to the overlay or a chosen element after layout.
  • Restores focus to the opening control or the overlay underneath.

Focus Targets

Call trap(root, { initialFocusRef, returnFocusRef }) when the overlay opens. The overlay supplies its own modal window or accessibility boundary.

Release

Call release() after dismissal. Pass { withoutFocusReturn: true } when another screen will manage the next focus target.

Backdrop manages this lifecycle for overlays built with it.