Skip to content

Instantly share code, notes, and snippets.

@chaance
Created November 21, 2021 16:02
Show Gist options
  • Save chaance/96c0f5d1d119096cbce0e1f92048ba2c to your computer and use it in GitHub Desktop.
Save chaance/96c0f5d1d119096cbce0e1f92048ba2c to your computer and use it in GitHub Desktop.
Remix route transition announcements
import * as React from "react";
import { useLocation, useTransition } from "remix";
function RouteAnnouncement({ getTitle = defaultGetTitle }) {
let location = useLocation();
let transition = useTransition();
let liveRegionRef = React.useRef(null);
React.useEffect(() => {
liveRegionRef.current = document.createElement("div");
liveRegionRef.current.setAttribute("role", "status");
liveRegionRef.current.id = "route-change-region";
// Visually hidden styles
liveRegionRef.current.style.border = "0";
liveRegionRef.current.style.clipPath = "inset(100%)";
liveRegionRef.current.style.clip = "rect(0 0 0 0)";
liveRegionRef.current.style.height = "1px";
liveRegionRef.current.style.margin = "-1px";
liveRegionRef.current.style.overflow = "hidden";
liveRegionRef.current.style.padding = "0";
liveRegionRef.current.style.position = "absolute";
liveRegionRef.current.style.width = "1px";
liveRegionRef.current.style.whiteSpace = "nowrap";
liveRegionRef.current.style.wordWrap = "normal";
document.body.appendChild(liveRegionRef.current);
}, []);
let firstRenderRef = React.useRef(true);
React.useEffect(() => {
if (firstRenderRef.current) {
firstRenderRef.current = false;
return;
}
if (liveRegionRef.current) {
let pageTitle = getTitle(location, transition);
liveRegionRef.current.textContent = pageTitle;
}
}, [location, transition, getTitle]);
return null;
}
function defaultGetTitle(location, transition) {
if (transition.state !== "idle") {
return document.title;
}
return location.pathname === "/" ? "Home page" : document.title;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment