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:
<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. 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 ( <nav> <menu role="menubar" onkeydown="{handleKeyDown}"> {menuItems.map((item, index) => <menuitem key="{item.label}" item="{item}" index="{index}" focusedindex="{focusedIndex}" setfocusedindex="{setFocusedIndex}"></menuitem> )} </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 (
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
The above is the detailed content of Building an Accessible Navigation Menubar with React Hooks. For more information, please follow other related articles on the PHP Chinese website!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Simple JavaScript functions are used to check if a date is valid. function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //test var

This article discusses how to use jQuery to obtain and set the inner margin and margin values of DOM elements, especially the specific locations of the outer margin and inner margins of the element. While it is possible to set the inner and outer margins of an element using CSS, getting accurate values can be tricky. // set up $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); You might think this code is

This article explores ten exceptional jQuery tabs and accordions. The key difference between tabs and accordions lies in how their content panels are displayed and hidden. Let's delve into these ten examples. Related articles: 10 jQuery Tab Plugins

Discover ten exceptional jQuery plugins to elevate your website's dynamism and visual appeal! This curated collection offers diverse functionalities, from image animation to interactive galleries. Let's explore these powerful tools: Related Posts: 1

http-console is a Node module that gives you a command-line interface for executing HTTP commands. It’s great for debugging and seeing exactly what is going on with your HTTP requests, regardless of whether they’re made against a web server, web serv

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

The following jQuery code snippet can be used to add scrollbars when the div content exceeds the container element area. (No demonstration, please copy it directly to Firebug) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools
