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

2

8

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!

Carmon answered 30/3, 2021 at 19:55 Comment(1)
it might be helpful to clarify the question title is upon parent mount/destroyDisaffirm
M
27

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/element-directives#transition-events

Edit 2023-06-23:

With Svelte 4, |local scope is now the default for transitions.

To make them global, use |global.

Maxia answered 31/3, 2021 at 7:41 Comment(0)
S
-2

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.

Stickybeak answered 30/3, 2021 at 22:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.