How to Use Animate in Svelte: Simple Guide with Examples
In Svelte, use the
animate directive to smoothly transition elements when their position or layout changes. Import flip from svelte/animate and apply it like animate:flip on elements that move or resize.Syntax
The animate directive in Svelte applies animation when an element's position or layout changes. You import an animation function like flip from svelte/animate and use it as animate:flip on the element.
Example parts:
import { flip } from 'svelte/animate': imports the animation function.animate:flip: directive added to the element to animate layout changes.
svelte
import { flip } from 'svelte/animate'; <!-- In markup --> <div animate:flip> <!-- content --> </div>
Example
This example shows a list of items that reorder when you click a button. The animate:flip directive smoothly moves the items to their new positions instead of jumping abruptly.
svelte
<script> import { flip } from 'svelte/animate'; let items = ['🍎', '🍌', '🍇', '🍓']; 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 Fruits</button> <ul> {#each items as item (item)} <li animate:flip>{item}</li> {/each} </ul>
Output
A button labeled 'Shuffle Fruits' and a list of fruit emojis that smoothly rearrange their order when the button is clicked.
Common Pitfalls
Common mistakes when using animate in Svelte include:
- Not providing a unique
keyin{#each}blocks, which breaks animation tracking. - Using
animateon elements that don't change position or layout, causing no visible effect. - Confusing
animatewithtransition, which animates element entry/exit instead of layout changes.
svelte
/* Wrong: Missing key in each block, animation won't work properly */ <ul> {#each items as item} <li animate:flip>{item}</li> {/each} </ul> /* Correct: Add unique key to track items */ <ul> {#each items as item (item)} <li animate:flip>{item}</li> {/each} </ul>
Quick Reference
Summary tips for using animate in Svelte:
- Import animations from
svelte/animate, likeflip. - Use
animate:flipon elements that move or resize. - Always provide unique keys in
{#each}blocks for correct animation. animateworks for layout changes, not for element entry/exit (usetransitionfor that).
Key Takeaways
Use the animate directive with imported functions like flip to animate layout changes.
Always provide unique keys in each blocks to enable proper animation tracking.
Animate is for smooth position or size changes, not for element entering or leaving.
Import animations from 'svelte/animate' and apply them as animate:flip on elements.
Avoid using animate on static elements that do not change layout or position.