Skip to content

Commit

Permalink
Focus State Update (#140)
Browse files Browse the repository at this point in the history
* Update NavigationFocusReset only on top-level page changes not search query changes

* edit so focus is reset on all page changes except filter and query changes

* use location.search instead to only check if query string changes
  • Loading branch information
adriencyberspace authored Aug 14, 2024
1 parent a9fe824 commit bea240e
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions app/components/ui/Navigation/NavigationFocusReset.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,28 @@
import React, { useEffect, useRef } from "react";
import { useLocation } from "react-router-dom";

// Resets focus state for a11y, by focusing and unfocusing an off-screen element at the top of the page when page location changes

export const NavigationFocusReset = () => {
/*
Resets focus state for a11y by focusing and unfocusing an off-screen element
at the top of the page when the page location changes.
The focus reset occurs on all page location changes except when only the query string changes.
*/
export const NavigationFocusReset: React.FC = () => {
const location = useLocation();
const hiddenInputRef = useRef<HTMLInputElement | null>(null);
const previousPathRef = useRef<string>("");

useEffect(() => {
if (hiddenInputRef.current) {
const currentPath = location.pathname + location.search;

const pathChanged = currentPath !== previousPathRef.current;

// Focus reset should occur if the path changed and it's not just a query string change
if (pathChanged && !location.search && hiddenInputRef.current) {
hiddenInputRef.current.focus();
hiddenInputRef.current.blur();
}

previousPathRef.current = currentPath;
}, [location]);

return (
Expand Down

0 comments on commit bea240e

Please sign in to comment.