VOOZH about

URL: https://dev.to/fazalshah/how-to-use-lottie-animations-in-svelte-and-sveltekit-24e5

⇱ How to Use Lottie Animations in Svelte and SvelteKit - DEV Community


Svelte's onMount lifecycle hook is perfect for integrating Lottie — it guarantees DOM availability before the animation loads. Here's how to set it up.

Get a Lottie File

Download a free animation from IconKing — no login needed, just preview and download .json or .lottie files. Place it in your static/animations/ folder (SvelteKit) or public/animations/ folder.

Install lottie-web

npm install lottie-web

Basic Svelte Component

Create src/lib/LottiePlayer.svelte:

<script>
 import { onMount, onDestroy } from "svelte";
 import lottie from "lottie-web";

 export let src = "/animations/default.json";
 export let loop = true;
 export let autoplay = true;
 export let width = "200px";
 export let height = "200px";

 let container;
 let animation;

 onMount(() => {
 animation = lottie.loadAnimation({
 container,
 renderer: "svg",
 loop,
 autoplay,
 path: src,
 });
 });

 onDestroy(() => animation?.destroy());
</script>

<div bind:this={container} style="width:{width};height:{height}"></div>

Use it anywhere in your app:

<script>
 import LottiePlayer from "$lib/LottiePlayer.svelte";
</script>

<LottiePlayer src="/animations/success.json" loop={false} />

Adding Controls

Export the animation instance so parent components can control playback:

<script>
 import { onMount, onDestroy } from "svelte";
 import lottie from "lottie-web";

 export let src;
 let container;
 export let animation = null;

 onMount(() => {
 animation = lottie.loadAnimation({
 container,
 renderer: "svg",
 loop: true,
 autoplay: false,
 path: src,
 });
 });

 onDestroy(() => animation?.destroy());
</script>

<div bind:this={container} style="width:200px;height:200px"></div>

Parent component:

<script>
 import LottiePlayer from "$lib/LottiePlayer.svelte";
 let animation;
</script>

<LottiePlayer src="/animations/loading.json" bind:animation />
<button on:click={() => animation?.play()}>Play</button>
<button on:click={() => animation?.pause()}>Pause</button>

SvelteKit SSR Note

onMount only runs in the browser, so lottie-web never runs on the server. This means no window is not defined errors — no extra configuration needed.

Where to Find Free Lottie Animations

IconKing is a free tool for previewing, editing, and downloading Lottie animations. You can tweak colors directly in the browser before downloading — handy for matching your Svelte app's design system. No account required.