0
0
SvelteHow-ToBeginner · 3 min read

How to Use Flip Animation in Svelte: Syntax and Example

In Svelte, use the flip function from svelte/animate to animate elements when their positions change. Apply animate:flip to elements inside a keyed {#each} block to smoothly transition their layout changes.
📐

Syntax

The flip animation is imported from svelte/animate and applied using the animate:flip directive on elements. It works best with keyed {#each} blocks to track element identity during reordering.

  • import { flip } from 'svelte/animate'; — imports the flip animation function.
  • animate:flip — directive to apply flip animation on an element.
  • Use with keyed {#each} blocks to detect element moves.
svelte
import { flip } from 'svelte/animate';

{#each items as item (item.id)}
  <div animate:flip>{item.name}</div>
{/each}
💻

Example

This example shows a list of items that reorder when you click a button. The flip animation smoothly moves items to their new positions.

svelte
<script>
  import { flip } from 'svelte/animate';
  let items = [
    { id: 1, name: 'Apple' },
    { id: 2, name: 'Banana' },
    { id: 3, name: 'Cherry' }
  ];

  function shuffle() {
    items = items
      .map(value => ({ value, sort: Math.random() }))
      .sort((a, b) => a.sort - b.sort)
      .map(({ value }) => value);
  }
</script>

<button on:click={shuffle}>Shuffle Items</button>

<ul>
  {#each items as item (item.id)}
    <li animate:flip>{item.name}</li>
  {/each}
</ul>
Output
A button labeled 'Shuffle Items' and a list of three fruits. Clicking the button randomly reorders the list with a smooth flip animation.
⚠️

Common Pitfalls

Common mistakes when using flip animation include:

  • Not using a keyed {#each} block, so Svelte can't track element identity and the animation won't work.
  • Applying animate:flip to elements that don't change position or size, resulting in no visible effect.
  • Forgetting to import flip from svelte/animate.
svelte
/* Wrong: no key, animation won't run properly */
{#each items as item}
  <div animate:flip>{item.name}</div>
{/each}

/* Right: keyed each block for flip animation */
{#each items as item (item.id)}
  <div animate:flip>{item.name}</div>
{/each}
📊

Quick Reference

  • Import flip: import { flip } from 'svelte/animate';
  • Use with keyed {#each} blocks: {#each items as item (item.id)}
  • Apply directive: animate:flip
  • Works best for reordering or layout changes.

Key Takeaways

Use animate:flip with keyed {#each} blocks to animate element position changes.
Always import flip from svelte/animate before using it.
Flip animation smoothly transitions layout changes like reordering or resizing.
Without keys, flip animation cannot track elements and won't work correctly.
Flip animation is best for elements that move or change size visually.