DEV Community

George Kemp
George Kemp

Posted on

A11y Hook for Hiding Outlines

Ever wish you could hide those pesky outlines that appear around all your inputs when they're focused, but also want to make sure your app caters to all users, the following hook listens to mouse click vs tab events to determine if a user is interacting with your site using keyboard or mouse and returns a boolean that you can use to control the outline on your components! Enjoy!

import { useEffect, useState } from "react";

export const useA11yOutline = () => {
  const [outline, setOutline] = useState(false);
  const handleKeydown = (e) => {
    const isTabEvent = e.keyCode === 9;

    if (isTabEvent) {
      setOutline(true);
    }
  }
  const handleClick = (e) => {
    setOutline(false);
  }
  useEffect(() => {
    window.addEventListener('keydown', handleKeydown);
    window.addEventListener('click', handleClick);
    return () => {
      window.removeEventListener('keydown', handleKeydown);
      window.removeEventListener('click', handleClick);
    }
  });
  return outline;
};

Top comments (0)