v-show alternative for Svelte

Viewed 1990

The case is that I'm showing Loading component on fetch request. I use store to set $loading to true and inside conditions is the Loading component. The problem is that the Loading component seems to be taking some time to show. It feels/looks like the reason is re-rendering of Loading component. So, I was looking for v-show like thing in Svelte, which I cannot find in Docs. (Don't get angry if its there, just tell me.)

Can anyone help with this case?

2 Answers

Either wrap it in an {#if someCondition} block, or slap a hidden={!someCondition} attribute on an element.

If you want a block of HTML that does not re-render when the condition is changed, here is a simple solution:

<script>
  // Show.svelte
  export let show = true;
</script>

<div class:hide={!show}>
  <slot />
</div>

<style>
  .hide {
    display: none !important;
  }
</style>

And then use the Show component to create that block:

<script>
  import Show from "Show.svelte";
  let show = true;
</script>
<button on:click={() => { show = !show}}>
  Click to Show/Hide Content
</button>
<Show {show}>
  <div>Content</div>
</Show>

I have posted the Show component as an npm package https://www.npmjs.com/package/svelte-show

Related