When a new page heading renders, I want to reset focus on that page, such that hitting <tab>
will cause the browser to go to the focusable/tabbable element after this primary page heading.
Asked
Active
Viewed 131 times
0

Devin Rhode
- 23,026
- 8
- 58
- 72
1 Answers
0
const PageTitle = ({title}) => {
const titleHeaderRef = useRef(null as null | HTMLHeadingElement);
useEffect(() => {
if (titleHeaderRef.current !== null) {
// First, make the element focus-able.
titleHeaderRef.current.setAttribute('tabIndex', '-1');
// Reset focus to this primary header.
titleHeaderRef.current.focus();
titleHeaderRef.current.blur();
// Finally, make the element non-focus-able.
titleHeaderRef.current.removeAttribute('tabIndex');
// To see this behavior in action, wrap this dom calls in a 5 second setTimeout, and tab around the page before this timeout is hit.
}
}, []);
return (
<Typography ref={titleHeaderRef}>
{title}
</Typography>
);
};

Devin Rhode
- 23,026
- 8
- 58
- 72
-
This SO page was helpful starting point: https://stackoverflow.com/questions/2520650/how-do-you-clear-the-focus-in-javascript – Devin Rhode Mar 28 '23 at 03:08