This post is a continuation of the course on Svelte. If you haven't read the previous parts of the series, we would recommend going through the post in the order.
Previous post - Svelte Reactivity
Svelte if
block is useful to display Svelte/HTML elements based on some condition. Rendering some part of the HTML based on some condition is also known as Conditional Rendering.
If
block can be simple with just one condition or you can have multiple conditions using the else
and else if
block. These help in making the conditional rendering in Svelte really simple.
{#if [condition]}
// HTML goes here
{:else if [condition]}
// HTML goes here
{:else}
// HTML goes here
{/if}
if
conditionelse if
condition helps in adding more logic if the first if
block is falseelse
condition executes when all the other conditions have been executed to false.Svelte offers an easy way to hide and show HTML elements based on some conditions. Let’s see an example of how to add an if
block
<script>
let showComments = true;
</script>
{#if showComments}
<h3>Comments blocks</h3>
{/if}
If you have an else condition and want to show different HTML elements, you can use the else syntax in Svelte.
<script>
let showComments = false;
</script>
{#if showComments}
<h3>Comments blocks</h3>
{:else}
<h3>Something else</h3>
{/if}
When having multiple conditions, you can use the else if syntax to cover all the different scenarios.
<script>
let shape = 'circle';
</script>
{#if shape == 'square'}
<h3>Sqaure</h3>
{:else if shape == 'circle'}
<h3>Circle</h3>
{:else if shape == 'triangle'}
<h3>Triangle</h3>
{:else}
<h3>Unknown Shape</h3>
{/if}
If / Else syntax makes it easy to write logic inside Svelte components as these are commonly used when it comes to real-world applications
Sriram is a content creator focused on providing quality content which provides value for the readers. He believe is constant learning and sharing those learning with the group. He is working as a lead developer and bulk of his experience is in working with multiple javascript frameworks such as Angular, React, Svelte. He is passionate about open source technologies and on his free time loves to develop games.
We will reach out when exciting new posts are available. We won’t send you spam. Unsubscribe at any time.