useFocusVisible

useFocusVisible manages focus interactions on the page and determines whether a focus ring should be shown. When using the useFocusVisible hook, if a user interacts with a mouse or by touch, then the focus indicator is not visible. When the user interacts with the keyboard however, the focus indicator will be visible.

References:

Accessibility

Examples

Buttons

import { useState } from 'react';
import { Flex, Text, useFocusVisible } from 'gestalt';
import { TOKEN_COLOR_BORDER_FOCUS } from 'gestalt-design-tokens';

export default function Example() {
  const { isFocusVisible } = useFocusVisible();
  const [focusedButton1, setFocusedButton1] = useState(false);
  const [focusedButton2, setFocusedButton2] = useState(false);

  return (
    <Flex
      alignItems="center"
      gap={4}
      height="100%"
      justifyContent="center"
      width="100%"
    >
      <Flex alignItems="center" direction="column" gap={12}>
        <Flex alignItems="center" direction="column" gap={4}>
          <Text>
            Using useFocusVisible(): Focus ring is only visible when using
            keyboard
          </Text>
          <button
            onBlur={() => setFocusedButton1(false)}
            onFocus={() => setFocusedButton1(true)}
            style={{
              outline:
                isFocusVisible && focusedButton1
                  ? `4px solid ${TOKEN_COLOR_BORDER_FOCUS}`
                  : undefined,
            }}
            type="button"
          >
            <Text>Button 1</Text>
          </button>
        </Flex>

        <Flex alignItems="center" direction="column" gap={4}>
          <Text>Not using useFocusVisible(): Focus ring is always visible</Text>
          <button
            onBlur={() => setFocusedButton2(false)}
            onFocus={() => setFocusedButton2(true)}
            style={{
              outline: focusedButton2
                ? `4px solid ${TOKEN_COLOR_BORDER_FOCUS}`
                : undefined,
            }}
            type="button"
          >
            <Text>Button 2</Text>
          </button>
        </Flex>
      </Flex>
    </Flex>
  );
}

Component quality checklist

Component quality checklist
Quality item
Status
Status description
Figma Library
Component is not currently available in Figma.
Responsive Web
Ready
Component responds to changing viewport sizes in web and mobile web.