How to disable transition animation on parent component mount and destroy in Svelte?

Viewed 1870

Right now, I have a menu which on click of a hamburger button can be expanded or collapsed. The default state of the menu is true meaning its expanded, but when I go to a different route where the menu is not there, it plays the collapsed animation. Here is a sample code:

<script>
 import { slide } from 'svelte/transition';
 let isExpanded = true; 
</script>

<button on:click={()=>isExpanded=!isExpanded}>Expand/Collapse</button>

{#if isExpanded}
  <nav transition:slide>
   Content
  </nav>
{/if}

<a href="/some-page">There is no menu in this page</a>

This is the current behavior of the code:

On page load/reload, the menu expand transition plays (weirdly, this only happens sometimes) and on clicking the link, the menu collapse transition plays for a split second while the redirect is happening.

I'm not sure if this is a bug or something wrong in my implementation. Either case, would be grateful if a workaround is provided for this.

Thanks in advance!

2 Answers

You can use the local scope on the transition so it only applies when the element is created/destroyed, and not when the parent is created/destroyed.

{#if isExpanded}
  <nav transition:slide|local>
   Content
  </nav>
{/if}

Depending on how your use case of going to a new route is implemented it may or may not work for you.

I've had mixed results with this, and there have been some bug fixes in recent versions of Svelte related to its use.

https://svelte.dev/docs#Transition_events

In svelte transitions are triggered only when the component is either mounted (added to the dom) or destroyed (removed from the dom), so the only way to disable transition on mount/destroy cycles is to not use it.

Related