Building an Accessible Navigation Menubar with React Hooks

RMAG news

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.

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:

<nav aria-label=“Accessible Menubar”>
<menu role=“menubar”>
<li role=“none”>
<a role=“menuitem” href=“/”>Home</a>
</li>
<li role=“none”>
<a role=“menuitem” href=“/about”>About</a>
</li>
<li role=“none”>
<button
role=“menuitem”
aria-haspopup=“true”
aria-expanded=“false”
>
Expand Me!
</button>
<menu role=“menu”>
<li role=“none”>
<a role=“menuitem” href=“/sub-item-1”>Sub Menu Item 1</a>
</li>
<li role=“none”>
<a role=“menuitem” href=“/sub-item-2”>Sub Menu Item 2</a>
</li>
</menu>
</li>
</menu>
</nav>

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. Very obviously, we need an overall menu component, as well as a menu item component.

Sub menus, despite being a recursive variant of the overall menu, benefits from being its own component. Submenus are styled differently, bur more importatly, has extra keyboard behaviors, as you’ll see later in this blog.

What’s more, some MenuItems have a sub menu while some don’t. The ones with sub menus will need to manage its state for sub menu open/close. So it needs to be its own component.

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. You will still need to call focus() on a ref, but you

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 (
<nav>
<menu role=“menubar” onKeyDown={handleKeyDown}>
{menuItems.map((item, index) =>
<MenuItem
key={item.label}
item={item}
index={index}
focusedIndex={focusedIndex}
setFocusedIndex={setFocusedIndex}
/>
)}
</menu>
</nav>
);
}

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 (
<li role=“none”>
<a
ref={linkRef}
role=“menuitem”
tabIndex={isFocused ? 0 : 1}
onFocus={handleFocus}
>
{item.label}
</a>
</li>
);
}

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

Please follow and like us:
Pin Share