DEV Community

Cover image for Remove outline when click but keep it when tab in React
Elecweb
Elecweb

Posted on • Updated on

Remove outline when click but keep it when tab in React

While I inspect f8 website, I see something interesting.

When you click on the button "Experience F8 2019", there's no blue outline that we hate (mostly designer). but when I tab on the website, I see the blue outline again.

So I search how to do it on the internet (aka Google) I found the way which explain really great.

https://hackernoon.com/removing-that-ugly-focus-ring-and-keeping-it-too-6c8727fefcd2

So I adapt it to react component. I think it might be useful for someone else that facing this problem.

import { useEffect } from 'react';

const handleFirstTab = event => {
  if (event.keyCode === 9) {
    document.body.classList.add('user-is-tabbing');
    window.removeEventListener('keydown', handleFirstTab);
  }
};

const RemoveFocusWhenNotTab = () => {
  useEffect(() => {
    window.addEventListener('keydown', handleFirstTab);
    return () => {
      window.removeEventListener('keydown', handleFirstTab);
    };
  });

  return null;
};

export default RemoveFocusWhenNotTab;

And you just render it in somewhere (I prefer render it in App.js)

You need to add style for focusable element (e.g., button) based on .user-is-tabbing class attaching to body element (I use styled-components for example).

const GlobalStyled = createGlobalStyle`
    body:not(.user-is-tabbing) button:focus {
        outline: none;
    }
`;

PS. I just hide outline until user tab. After that when user click it, it'll show outline again. There's a way to hide outline again when user click but I think it's too much. If you're interested to do it, the website I reference also show how to do it which you can adapt with RemoveFocusWhenNotTab component easily

Top comments (0)