A team building a React-based progressive web app with client-side routing through React Router set out to make the main menu keyboard operable: tab through top-level items, reach the sub-menus that otherwise appear on hover, and keep a visible focus ring throughout. The path to a working solution ran through several failed or partial approaches, each revealing a way that single page applications break assumptions inherited from full page loads.

Making sub-menus reachable by keyboard

The original CSS swapped visibility between visible and hidden on hover of the parent container. That serves mouse users, but focus does not move into an element set to visibility: hidden — the same holds for display: none. The team dropped visibility in favor of a large negative position offset instead:

.menu-item {
  position: relative;
}

.sub-menu {
  position: absolute
  left: -100000px; /* Kicking off  the page instead of hiding visiblity */
}

.menu-item:hover .sub-menu {
  left: 0;
}

Mouse behavior was unchanged, yet the sub-menu still stayed invisible while focus traveled inside it. The fix was to combine :focus and :focus-within on the parent container:

.menu-item {
  position: relative;
}

.sub-menu {
  position: absolute
  left: -100000px;
}

.menu-item:hover .sub-menu,
.menu-item:focus .sub-menu,
.menu-item:focus-within .sub-menu {
  left: 0;
}

Now each sub-menu appears as its links receive focus; focus moving to the next sub-menu hides the first and reveals the second. The pull request was merged.

What the next day in staging exposed

Using the menu for real surfaced two problems. After selecting an item, by click or by tab, the menu failed to hide. Mouse users had to click somewhere on empty space to clear focus; keyboard users were stuck, since esc and other key combinations did nothing. Their only escape was to tab through the rest of the menu until focus landed on an element that didn't leave a dropdown obscuring the view.

Selection retains focus on the chosen item, and because client-side routing updates only part of the page, nothing performs the focus reset a full page reload would provide. The second problem: the "Jump to Content" link became hard to use. Users expect one tab press to land on it, and the menu implementation broke that expectation.

Attempts at clearing focus

The quickest option was an onClick prop on React Router's Link that calls document.activeElement.blur():

const Menu = () => {
  const clearFocus = () => {
    document.activeElement.blur();
  }

  return (
    <ul className="menu">
      <li className="menu-item">
        <Link to="/" onClick={clearFocus}>Home</Link>
      </li>
      <li className="menu-item">
        <Link to="/products" onClick={clearFocus}>Products</Link>
        <ul className="sub-menu">
          <li>
            <Link to="/products/tops" onClick={clearFocus}>Tops</Link>
          </li>
          <li>
            <Link to="/products/bottoms" onClick={clearFocus}>Bottoms</Link>
          </li>
          <li>
            <Link to="/products/accessories" onClick={clearFocus}>Accessories</Link>
          </li>
        </ul>
      </li>
    </ul>
  );
}

This closes the menu on selection, but pressing tab afterward moves focus to the next link rather than to the "Jump to Content" link. Programmatically sending focus to an element high in the DOM was the obvious next step, so that tabbing after navigation begins near the top of the page.

Forcing focus onto <body> failed — the body is not interactive and cannot receive focus. Focusing the header logo was workable in principle, since it is a link home, but in this app the logo sits below the "Jump to Content" link in the DOM, so reaching that link would require shift + tab.

The focus-reset anchor

The solution was to render an interactive element — an anchor — above the "Jump to Content" link, styled invisible and removed from normal tab order. Selecting a menu item forces focus to it, so the next tab reaches the jump link and the sub-menu hides immediately.

const App = () => {
  const focusResetRef = React.useRef();

  const handleResetFocus = () => {
    focusResetRef.current.focus();
  };

  return (
    <Fragment>
      <a
        ref={focusResetRef}
        href="javascript:void(0)"
        tabIndex="-1"
        style={{ position: "fixed", top: "-10000px" }}
        aria-hidden
      >Focus Reset</a>
      <a href="#main" className="jump-to-content-a11y-styles">Jump To Content</a>
      <Menu onSelectMenuItem={handleResetFocus} />
      ...
    </Fragment>
  )
}
  • href is javascript:void(0), so an accidental interaction — pressing return right after selecting an item, for instance — does nothing and leaves the URL unchanged.
  • tabIndex="-1" keeps the element out of normal focus order, which also ensures the first tab after a page load lands on "Jump to Content" rather than the anchor.
  • position: fixed in the inline style pushes the element outside the viewport and out of document flow, so it consumes no vertical space.
  • aria-hidden keeps screen readers from announcing it.

Clearing hover as well

A mega menu that survives a mouse click carries the same frustration: the only way to drop the :hover state is to move the pointer onto a part of the page outside the menu. A React clearHover class forces the hover state to clear:

// Menu.jsx
const Menu = (props) => {
  const { onSelectMenuItem } = props;
  const [clearHover, setClearHover] = React.useState(false);

  const closeMenu= () => {
    onSelectMenuItem();
    setClearHover(true);
  }

  React.useEffect(() => {
    let timeout;
    if (clearHover) {
      timeout = setTimeout(() => {
        setClearHover(false);
      }, 0); // Adjust this timeout to suit the applications' needs
    }
    return () => clearTimeout(timeout);
  }, [clearHover]);

  return (
    <ul className={`menu ${clearHover ? "clearHover" : ""}`}>
      <li className="menu-item">
        <Link to="/" onClick={closeMenu}>Home</Link>
      </li>
      <li className="menu-item">
        <Link to="/products" onClick={closeMenu}>Products</Link>
        <ul className="sub-menu">
          {/* Sub Menu Items */}
        </ul>
      </li>
    </ul>
  );
}

With this in place the menu hides immediately on click and on keyboard selection, and the tab after navigation goes to "Jump to Content" — close to what the browser does on a full reload.

Packaging the pattern

In the production version the team wrapped the pattern in a React Context, with the Provider around the Header component and the focus-reset element inserted just before the Provider's children so it lands above the jump link in the DOM. The reset function is then reachable through a hook instead of prop drilling, and the pattern is reusable on other projects. A Code Sandbox compares the three iterations so the pain points of the earlier ones are visible next to the final behavior.

The implementation has not shipped to real users, so there is no data or user feedback yet, and the team describes itself as practitioners rather than accessibility experts, open to correction.