How change component transition speed properly?

66 views Asked by At

My goal is to provide transition speed via component properties and to set different values for growing and shrinking. So far I managed to achieve this by changing component style programmatically.

<script>
    let isFullHeight = false
    export let fullHeight = 400
    export let growDurationMs = 1234
    export let shrinkDurationMs = 567
</script>
<div id="container" style={isFullHeight ?
    `height: ${fullHeight}px; transition: height ${growDurationMs}ms;` :
    `transition: height ${shrinkDurationMs}ms;`}
    on:click={() => isFullHeight = !isFullHeight}>
</div>

This does the job, but maybe there is more idiomatic/elegant way to do this.

Link to Svelte REPL with this example

1

There are 1 answers

0
xuesheng On

This answer is based on Daniel's comment above. The idea is to represent style as an object to make it more readable and then convert it to a style string.

<script>
  ...
  $: styleObj = isFullHeight ? {
      height: `${fullHeight}px`,
      transition: `height ${growDurationMs}ms`
    } : {
      transition: `height ${shrinkDurationMs}ms`
    }

  $: style = Object.entries(styleObj).map(([k, v]) => `${k}:${v}`).join(';')

Now the component looks much cleaner:

<div {style}>
  ...