Devin Rhode
Devin Rhode

Reputation: 25377

Reset focus when <h1> renders in react

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.

Upvotes: 0

Views: 763

Answers (1)

Devin Rhode
Devin Rhode

Reputation: 25377

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>
  );
};

Upvotes: 0

Related Questions