#transition:persist with navigation
3 messages · Page 1 of 1 (latest)
Astro provides a way to persist components and HTML elements across page navigations using the transition:persist directive. This allows components to continue existing even as you navigate to another page that contains the same component. This works for both forwards and backwards navigation.
For example, if you have a video component, it will continue to play as you navigate to another page that contains the same video element.
<video controls="" autoplay="" transition:persist>
<source src="<https://ia804502.us.archive.org/33/items/GoldenGa1939_3/GoldenGa1939_3_512kb.mp4"> type="video/mp4">
</video>
However, if you want to persist the component but not its state, you can use the transition:persist-props directive. By default, when you add transition:persist to a component, the state is retained upon navigation, but your component will re-render with new props. You can override this behavior by setting transition:persist-props in addition to transition:persist. Adding this directive will keep a component’s existing props (not re-render with new values) in addition to maintaining its existing state.
<Counter client:load transition:persist transition:persist-props initialCount={5} />
Remember to opt in to using view transitions on individual pages by importing and adding the <ViewTransitions /> routing component to <head> on every desired page.
---import { ViewTransitions } from 'astro:transitions';---
<html lang="en">
<head>
<title>My Homepage</title>
<ViewTransitions />
</head>
<body>
<h1>Welcome to my website!</h1>
</body>
</html>