Develop ultra fast with Prismane 🎉

useFocusTrap

useFocusTrap hook provides a simple way to trap the user's focus.

Import

import { useFocusTrap } from "@prismane/core/hooks";

Usage

By default, the useFocusTrap hook focuses the first focusable element in the container, to which the ref is passed. As you can see, in the example below, we pass the ref to a Stack container, and the first input of the container is focused.

function Demo() {
  const ref = useFocusTrap();

  return (
    <Flex direction="column" gap={fr(2)} w="300px">
      <TextField />
      <Stack ref={ref}>
        <TextField placeholder="I should be focused" />
        <TextField />
      </Stack>
    </Flex>
  );
}

Toggle Hook

The functionality of the hook can be toggled, if we pass a boolean value as the isOpen parameter of the hook.

function Demo() {
  const [open, setOpen] = useState(false);

  const ref = useFocusTrap(open);

  return (
    <Flex direction="column" gap={fr(2)} w="300px">
      <TextField />
      <Stack ref={ref}>
        <TextField placeholder="I should be focused" />
        <TextField />
      </Stack>
      <Button onClick={() => setOpen(!open)}>Toggle Hook</Button>
    </Flex>
  );
}

Initial Focused Element

You can set the initial element that will be focused, by giving it an attribute of data-initialfocus.

function Demo() {
  const [open, setOpen] = useState(false);

  const ref = useFocusTrap(open);

  return (
    <Flex direction="column" gap={fr(2)} w="300px">
      <TextField />
      <Stack ref={ref}>
        <TextField placeholder="I am the first, but I am not focused" />
        <TextField placeholder="I should be focused" data-initialfocus />
      </Stack>
      <Button onClick={() => setOpen(!open)}>Toggle Hook</Button>
    </Flex>
  );
}

API

Parameters

NameTypeDescriptionDefault
isOpenbooleanThe boolean that toggles the hook.true

Return Value

NameTypeDescription
refRef<any>The ref that should be passed to the container with the focusable elements.