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 ✌️

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →