Skip to content

Instantly share code, notes, and snippets.

@jafin
Last active August 25, 2020 02:56
Show Gist options
  • Save jafin/aae4132067524d88f6935609cfe85e62 to your computer and use it in GitHub Desktop.
Save jafin/aae4132067524d88f6935609cfe85e62 to your computer and use it in GitHub Desktop.
FocusOnRouteChange for React Router -- code adapted from https://github.com/ReactTraining/react-router/issues/5210 . Support Focus Accessibility on route navigation changes
import React, { useRef, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
let prevPathName: string | null = null;
export const FocusOnRouteChange: React.FC = ({ children }) => {
const history = useHistory();
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
history.listen(({ pathname }) => {
// don't refocus if only the query params/hash have changed
if (pathname !== prevPathName) {
ref.current?.focus();
// prevent jank if focusing causes page to scroll
window.scrollTo(0, 0);
prevPathName = pathname;
}
});
});
return (
<div ref={ref} tabIndex={-1} style={{ outline: 'none' }}>
{children}
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment