Getting Fancy with Astro View Transitions
Tags in this post:
Again, Astro Tutorials to the rescue. Here’s a synopsis of the changes (including fixing Dark Mode.)
Adding Astro’s View Transition Component
Too easy… If you don’t have a BaseHead element like this that all of your layouts share, I suggest making one.
// /src/components/BaseHead.atro
import { ViewTransitions } from "astro:transitions";
...
// at the bottom of the template:
<ViewTransitions />
And we’re done! Almost…
Fixing Dark Mode
The ThemeIcon component doesn’t work once you transition away, so there’s a quick fix for that, along with one that will fix flashing. First, we need to wrap the javascript for our mode changer in a special event handler:
<!-- /src/components/ThemeIcon.astro -->
<script is:inline>
document.addEventListener("astro:page-load", () => {
const theme = (() => {
...
})
});
</script>
The same event listener will need to be added to any other scripts you have that need to run onload.
And to fix the flashing we just add a new script tag to the ThemeIcon component:
<!-- /src/components/ThemeIcon.astro -->
<script>
document.addEventListener("astro:after-swap", () => {
localStorage.theme === "dark"
? document.documentElement.classList.add("dark")
: document.documentElement.classList.remove("dark");
});
</script>
That was quick. I think I’ll add tags now too.