Astro JS - View Transition



View Transition

View Transition is a feature in astro, that updates the page content without the browsers normal, full-page navigation refresh. It provide a seamless animations between pages, making a better user experience. Astro uses browser's view transition API enable transition between pages in website.

Features of View Transition

  • Provide builtin animations such as, fade, slide, between page loads
  • Support for both forwards and backwards navigation animations.
  • The animations are fully customizable.
  • An option to setup fallback behavior for browsers that do not support the view transition API.
  • Automatic support for prefers-reduced-motion.

Use View Transitions in Astro

Step 1: Add clientRouter Component

The <ClientRouter /> component is used to control page transitions as you navigate away to another page. Add this component to a single pages <head>.

---
    import { ClientRouter } from 'astro:transitions';
---
<html lang="en">
    <head>
        <title>My Homepage</title>
        <ClientRouter />
    </head>
    <body>
        <h1>Welcome to my website!</h1>
    </body>
</html>

Step 2: Customizing Animations

You can customize all aspects of a transition with any CSS animation properties. To customize a built-in animation, first import the animation from astro:transitions, and then pass in customization options. The example below customizes the duration of the built-in fade animation

---
import { fade } from 'astro:transitions';
---

<header transition:animate={fade({ duration: '0.4s' })}>

Step 3: Fallback Behavior

Astro automatically handles unsupported browsers by falling back to standard navigation while preserving functionality. You can customize the fallback behavior by passing in a fallback option to the <ClientRouter /> component.

Router Control

The <ClientRouter /> component router handles navigation by listening to:

  • Clicks on <a> elements.
  • Backwards and forwards navigation events.

The following options allow you to further control when navigation occurs within the router:

  • data-astro-reload: an <a> tag attribute to force a full-page navigation
  • data-astro-history="auto | push | replace": an <a> tag attribute to control the browsers history
  • navigate(href, options): a method available to any client script or client component to trigger navigation
Advertisements