Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a conditional transition in Svelte?

Tags:

svelte

In Svelte we can add transitions with:

<div in:fade={{duration: 150}}>...</div>

It's also possible to have conditional HTML attributes with:

<input disabled={null}>

This doesn't work with transitions:

<div in:fade={null}>...</div>

Which throws this error as it expects a config object:

Cannot read property 'delay' of null

So what would would be the appropriate way of adding a conditional transition in Svelte?

Other than:

{#if animate}
    <div in:fade></div>
{:else}
    <div></div>
{/if}
like image 250
Pier Avatar asked May 14 '20 19:05

Pier


2 Answers

You can pass in a configuration object to the transition with a duration of 0 (effectively instantaneously):

<script>
    import { fade } from 'svelte/transition'
    
    export let animate
</script>

<div in:fade={{ duration: animate ? 500 : 0 }}>
    ...
</div>
like image 103
Stephane Vanraes Avatar answered Nov 12 '22 18:11

Stephane Vanraes


You could also solve this with a wrapper around the transition function. Demo here.

<script>
  import { fly, slide } from 'svelte/transition';
    
  export let animate = true;
    
  function maybe(node, options) {
    if (animate) {
      return options.fn(node, options);
    }
  }
</script>

<h1 in:maybe={{ fn: fly, x: 50 }} out:maybe={{ fn: slide }}>Hello!</h1>
like image 23
Andrew Childs Avatar answered Nov 12 '22 20:11

Andrew Childs