"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Building an Accessible Navigation Menubar with React Hooks

Building an Accessible Navigation Menubar with React Hooks

Published on 2024-08-25
Browse:839

Building an Accessible Navigation Menubar with React Hooks

Accidentally published! Please come back later for more!

Introduction

Creating accessible web applications is not just a good practice — it's a necessity now. Recently, I had the opportunity to build a navigation menubar with a focus on a11y. As I was researching, I realized how most menubars out there don't comply to the ARIA pattern. For example, instead of tabbing through menu items, did you know that a menubar should be navigated with arrow keys and manage its own focus?

Though I did find some tutorials, I ended up not following them completely. I'm writing this because I think what I ended up building is worth sharing — if you also have an affinity to small components and custom hooks.

Though I will structure this blog with some development steps, my goal is not to write a step-by-step guide. I trust you to know React basics, and how custom hooks work.

I'm only sharing the key implementation details now, but I do plan to update this article with a code sandbox example in the future when I have more time.

What are we building?

For this blog, we are building towards a nav menu bar, like the ones you see on the top or on the side of many web applications. In this menu bar, some menu items may have sub menus, which will open/close on mouse enter/leave.

HTML Markup

First and foremost, semantic HTML and appropriate roles and ARIA attributes are essential to accessibility. For the menubar pattern, you can read more from the official doc here.

Here's an example for appropriate HTML markup:

Notice we are using the button tag for semantic HTML. The button should also have aria-haspopup to alert screen readers. Lastly, the appropriate aria-expanded attribute should be assigned depending on the menu state.

Components

Let's walk through the components we need. Obviously, we need an overall menu component, as well as a menu item component.

Some menu items have a sub menu while some don't. The menu items with sub menus will need to manage their states for sub menu open/close on hover and keyboard events. So it needs to be its own component.

Sub menus need to be its own component as well. Though sub menus are also just containers for menu items, they don't manage their states or handle keyboard events. This differentiates them from the top level nav menu.

I ended up writing these components:

  • NavMenu for the outmost layer of menubars.
  • MenuItem for individual menu items.
    • MenuItemLink
    • MenuItemWithSubMenu
  • SubMenu for the expanded sub menu. MenuItem can be recursively nested within the sub menu.

Focus Management

In very plain words, "focus management" just means the component needs to know which child has focus. So when the user's focus leaves and comes back, the previously focused child will be refocused.

A common technique for focus management is "Roving Tab Index", where the focused element in the group has a tab index of 0, and other elements has a tab index of -1. This way, when the user returns to the focus group, the element with tab index 0 will automatically have focus.

A first implementation for NavMenu can look something like this:

export function NavMenu ({ menuItems }) {
  // state for the currently focused index
  const [focusedIndex, setFocusedIndex] = useState(0);

  // functions to update focused index
  const goToStart = () => setCurrentIndex(0);
  const goToEnd = () => setCurrentIndex(menuItems.length - 1);
  const goToPrev = () => {
    const index = currentIndex === 0 ? menuItems.length - 1 : currentIndex - 1;
    setCurrentIndex(index);
  };
  const goToNext = () => {
    const index = currentIndex === menuItems.length - 1 ? 0 : currentIndex   1;
    setCurrentIndex(index);
  };

  // key down handler according to aria specification
  const handleKeyDown = (e) => {
    e.stopPropagation();
    switch (e.code) {
      case "ArrowLeft":
      case "ArrowUp":
        e.preventDefault();
        goToPrev();
        break;
      case "ArrowRight":
      case "ArrowDown": 
        e.preventDefault();
        goToNext();
        break;
      case "End":
        e.preventDefault();
        goToEnd();
        break;
      case "Home":
        e.preventDefault();
        goToStart();
        break;
      default:
        break;
    }
  }

  return (
    
  );
}

The e.preventDefault() is there to prevent things like ArrowDown scrolling the page.

Here's the MenuItem component. Let's ignore items with sub menu just for a second. We are using useEffect, usePrevious and element.focus() to focus on the element whenever focusedIndex changes:

export function MenuItem ({ item, index, focusedIndex, setFocusedIndex }) {
  const linkRef = useRef(null);
  const prevFocusedIndex = usePrevious(focusedIndex);
  const isFocused = index === focusedIndex;

  useEffect(() => {
    if (linkRef.current 
      && prevFocusedIndex !== currentIndex 
      && isFocused) {
      linkRef.current.focus()
    }
  }, [isFocused, prevFocusedIndex, focusedIndex]);

  const handleFocus = () => {
    if (focusedIndex !== index) {
      setFocusedIndex(index);
    }
  };

  return (
    
  • {item.label}
  • ); }

    Notice it's the a tag that should have the ref (button for menu item with submenus), so when they are focused on, default keyboard behaviors will kick in as expected, like navigation on Enter. What's more, the tab index is being properly assigned depending on the focused element.

    We are adding an event handler for focus event in case the focus event is not from a key/mouse event. Here's a quote from the web doc:

    Don't assume that all focus changes will come via key and mouse events: assistive technologies such as screen readers can set the focus to any focusable element.

    Tweak #1

    If you follow the useEffect described above, you'll find that the first element will have focus even if the user hasn't used keyboard to navigate. To fix this, we can check the active element and only call focus() when the user has started some keyboard event, which shifts the focus away from body.

      useEffect(() => {
        if (linkRef.current 
          && document.activeElement !== document.body // only call focus when user uses keyboard navigation
          && prevFocusedIndex !== focusedIndex
          && isCurrent) {
          linkRef.current.focus();
        }
      }, [isCurrent, focusedIndex, prevFocusedIndex]);
    

    Logic Reuse and Custom Hook

    So far, we have functional NavMenu and MenuItemLink components. Let's move on to menu item with sub menus.

    As I was quickly building it out, I realized that this menu item will share the majority of the logic

    Release Statement This article is reproduced at: https://dev.to/godsamit/building-an-accessible-navigation-menubar-with-react-hooks-blh?1 If there is any infringement, please contact [email protected] to delete it
    Latest tutorial More>

    Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

    Copyright© 2022 湘ICP备2022001581号-3