Basic Transitions with `transition:` in Svelte
Introduction to Transitions in Svelte
In the previous lesson, you learned how to use dynamic class binding and CSS transitions to create interactive components in Svelte. Now, we’ll take a step further and explore Svelte’s built-in transition system, which allows you to animate elements as they enter or leave the DOM. Transitions are a powerful way to enhance the user experience by making your application feel more dynamic and polished.
Svelte provides several built-in transition functions, such as fade and slide, which you can use to animate elements with minimal effort. These transitions are applied using the transition: directive, making it easy to add animations to your components. By the end of this lesson, you’ll understand how to use these transitions to create smooth and engaging animations in your Svelte applications.
Setting Up a Basic Svelte Component
To get started, let’s create a simple Svelte component that toggles the visibility of an element. We’ll use the $state rune in Svelte to manage the visibility state and an onclick event handler to toggle it. Here’s the basic setup:
In this example:
- We define a state variable
showusing$state(true), which initializes totrue. - The
onclickevent handler toggles the value ofshowbetweentrueandfalse. - The
{#if}block conditionally renders the<p>element based on the value ofshow.
When you click the button, the text will appear or disappear instantly. In the next section, we’ll add transitions to make this change smoother.
Applying Transitions with `transition:`
Now, let’s enhance our component by adding transitions using the transition: directive. Svelte provides several built-in transition functions, such as fade and slide, which you can import from svelte/transition. Here’s how to apply these transitions to our example:
In this updated example:
- We import the
fadeandslidetransitions fromsvelte/transition. - The
transition:fadedirective is applied to the<p>element, which will now fade in and out when it enters or leaves the DOM.
When you click the button, the text will smoothly fade in and out instead of appearing or disappearing instantly. You can also combine multiple transitions for more complex effects. For example, you can use transition:slide to make the text slide in and out:
Note: In Svelte, only one transition can be applied to an element at a time. If you try to use multiple transitions (e.g., transition:fade transition:slide), it will result in an error. To combine multiple effects, consider using a custom transition or pairing transitions with animations for more complex behaviors. Use transitions thoughtfully to maintain smooth and intuitive animations in your components.
