How add transitions to Astro pages
Embracing Astro, you get several benefits, including performance and SEO (Search Engine Optimization) but the transitions between one page and the other will be handled via the regular, full-page browser navigation. There is nothing wrong with that, but with a few lines of Code, Astro can give your site the taste of Single Page Applications (SPA) for a seamless animation between pages. In this post, we’ll see how to integrate Astro transitions in single pages, or in your entire website.
Adding view transitions to a single page
The integration is straightforward: you just need to import the ‘ViewTransitions’ module in the script part of your Astro component, and to add ‘ViewTransitions’ in the ‘head’ section of the template part of your component.
Here’s an example:
// index.astro
---
import { ViewTransitions } from "astro:transitions";
---
<head>
//...
<!-- Render the view transitions component -->
<ViewTransitions />
</head>
// ...
Adding view transitions to the entire site
In this case, you’ll have to make the integrations discussed for the single page in a layout adopted for the entire site, always including the ‘ViewTransitions’ component in the head section.
In this way, the transitions will be applied to the whole website.
Here’s an example:
// MainHead.astro
--
// component imports
import { ViewTransitions } from "astro:transitions";
...
---
<html lang="en">
<head>
...
<!-- Render the view transitions component -->
<ViewTransitions />
</head>
...
</html>
Conclusion
With just a couple of lines of code, you’ll get yourself a much smoother website, resembling the experience of Single Page Applications (SPA).
For a more advanced use of Astro Transitions, you can check out the Astro official documentation page.