T8 React Router
Animated view transitions
Animated transitions between different routes can be achieved by using the browser's View Transition API and the optional callback parameter of useRoute() can be used to set up such a transition.
+ import { flushSync } from "react-dom";
import { A, useRoute } from "@t8/react-router";
+ function renderViewTransition(render) {
+ if (document.startViewTransition) {
+ document.startViewTransition(() => {
+ flushSync(render);
+ });
+ }
+ else render();
+ }
export const App = () => {
- let { at } = useRoute();
+ let { at } = useRoute(renderViewTransition);
return (
// Content
);
};
In the example above, the renderViewTransition() function passed to useRoute() calls document.startViewTransition() from the View Transition API to start a view transition and React's flushSync() to apply the DOM changes synchronously within the view transition, with the visual effects defined with CSS. We also check whether document.startViewTransition is supported by the browser and resort to regular rendering if it's not.
To trigger a transition only with specific links, the options parameter of the useRoute() callback can be used to add a condition for the view transitions. In the example below, we'll only trigger a view transition with the links whose data-id attribute, available via options.id, is among the listed on viewTransitionLinkIds.
+ let viewTransitionLinkIds = new Set([/* ... */]);
function renderViewTransition(render, options) {
- if (document.startViewTransition) {
+ if (document.startViewTransition && viewTransitionLinkIds.has(options.id)) {
document.startViewTransition(() => {
flushSync(render);
});
}
else render();
}