@k8ordo/router

Transitions

Add a cross-fade or a slide to page changes with React’s <ViewTransition>. Filter on the transition types the router adds to page changes, and only page changes animate.

On this page

Cross-fade

src/shell.tsx
import { Outlet } from '@k8ordo/router';
import { ViewTransition } from 'react';

export function Shell() {
  return (
    <>
      <header>…</header>
      <ViewTransition
        default="none"
        update={{ navigation: 'auto', default: 'none' }}
The `<ViewTransition>` stays mounted and only its content changes, so this goes in `update`
      >
        <Outlet />
      </ViewTransition>
    </>
  );
}

Wrap <Outlet />, where pages render, in a <ViewTransition>. auto is the browser’s own cross-fade.

This site wraps its pages in the same <ViewTransition>. Open another page from the sidebar, and the content cross-fades.

Under @k8ordo/framework, wrap a layout’s children in the same <ViewTransition>. Layouts are covered in Routing for @k8ordo/framework.

Transition types

The router gives every render that changes the page the transition type navigation. Key update on navigation and set both the default prop and update’s default to none, and only renders of that type animate.

Transitions run a <ViewTransition> too, not just page changes. That includes any update wrapped in startTransition, such as the action @k8ordo/ui’s Button runs. Without the filter, every press cross-fades the whole page.

A state update that changes only the query does not change the page, so it does not animate.

Slide on back

src/shell.tsx
<ViewTransition
  default="none"
  update={{
    'navigation-push': 'slide-forward',
    'navigation-replace': 'slide-forward',
    'navigation-traverse': 'slide-back',
    default: 'none',
  }}
>
  <Outlet />
</ViewTransition>

Besides navigation, the router adds one of navigation-push, navigation-replace and navigation-traverse. A link click and navigateTo are push. Passing { history: 'replace' } to navigateTo makes it replace. The browser’s back and forward are traverse.

src/app.css
@keyframes slide-from-right {
  from {
    opacity: 0;
    translate: 32px 0;
  }
}

@keyframes slide-from-left {
  from {
    opacity: 0;
    translate: -32px 0;
  }
}

::view-transition-new(.slide-forward) {
  animation: 200ms ease-out both slide-from-right;
}

::view-transition-new(.slide-back) {
  animation: 200ms ease-out both slide-from-left;
}

Each value in update becomes a view transition class. Style each class through ::view-transition-old() and ::view-transition-new().

Reduced motion

src/app.css
@media (prefers-reduced-motion: reduce) {
  ::view-transition-group(*),
  ::view-transition-old(*),
  ::view-transition-new(*) {
    animation: none;
  }
}

This turns view transition animations off when prefers-reduced-motion is reduce. @k8ordo/ui’s stylesheet already includes it, so only an app without @k8ordo/ui needs this rule.

k8ordo

React libraries that use Baseline features without holding back.