A11y Hook for Hiding Outlines
George Kemp
Posted on October 10, 2019
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;
};
💖 💪 🙅 🚩
George Kemp
Posted on October 10, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript Just a friendly reminder that React isn't really Just JavaScript (Don't nest Functional Components)
November 6, 2021
typescript State machine advent: Let the machine handle accessibility for you (18/24)
December 19, 2019