javascript / expert
Snippet
Native View Transitions with Svelte State Updates
The View Transition API creates seamless animations between DOM states. By wrapping a Svelte state update in startViewTransition, the browser automatically captures snapshots and cross-fades between the old and new component layouts.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>let view = $state('list');function navigate(nextView) {if (!document.startViewTransition) {view = nextView;return;}document.startViewTransition(() => {view = nextView;});}</script><button onclick={() => navigate('grid')}>Switch View</button>
svelte
Breakdown
1
if (!document.startViewTransition)
Feature detection for progressive enhancement in unsupported browsers.
2
document.startViewTransition(() => { view = nextView; });
Signals the browser to animate the transition while the state update modifies the DOM.
3
view = nextView;
The actual reactive state update that changes the rendered component or layout.