DEV Community

Cover image for How to animate state change in Svelte
Abdulmumin yaqeen
Abdulmumin yaqeen

Posted on • Originally published at yaqeen.me

6 2 2

How to animate state change in Svelte

Svelte is amazing, and in this article we will go through how you can animation/transition between components in svelte.

If you’re to do this with CSS, you will find it almost impossible if what you’re changing is not a CSS property. With the recent development in view-transitions-api, we’re moving to a phase were it going to become easier to do this.

How?

we can achieve this with the {#key …} block, which is part of the super useful list of logic blocks Svelte provides.

view the complete list of logic blocks here

The {#key …} is not built specifically for animating or transition, but it listens to changes in the expression changes and it destroys and recreate it content whenever the expression changes changes.

With this advantage, we can create a transition either using svelte built in transitions capabilities or make a custom one with CSS.

Example

This simple syntax for this is:

{#key value}
    <div transition:fade>{value}</div>
{/key}
Enter fullscreen mode Exit fullscreen mode

Here we are going to wrap our content around the key and we’re going apply a slide transition whenever the image changes.

<script>
    let images = ['/carousel.png', '/carousel1.png', '/carousel2.png', '/carousel3.png'];

    let currentIndex = 0;
    let image = images[currentIndex];

    onMount(() => {
        // Start the carousel
        interval = setInterval(() => {
            currentIndex = (currentIndex + 1) % images.length;
            image = images[image];
        }, 3000);
    });
</script>

<div>
    <div>
        {#key image}
            <div transition:slide>
                <img src={image} alt="" />
            </div>
        {/key}
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

One thing I want to clarify is that, in both examples, no just values can be passed to the key, you can also feed it an expression, and will perform the same.

Svelte is beautiful, I love it, if you’re here, you definitely love it too. Share the knowledge with others that might find it useful.

Peace ✌️

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

If this article connected with you, consider tapping ❤️ or leaving a brief comment to share your thoughts!

Okay