Last active
August 25, 2020 02:56
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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