Svelte Basics - If / Else / If Else block - Part 4

25 Mar, 2022, 2 min read

Svelte Training Course - Free Course

5 part series

Svelte Basics - If / Else / If Else block - Part 4

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

Why do we need If block in Svelte?

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.

How to define an If block in Svelte

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}
  1. It starts with one or more conditions that can be added to the first line.
  2. You can have one or more lines of simple HTML / Svelte components after the if condition
  3. else if condition helps in adding more logic if the first if block is false
  4. else condition executes when all the other conditions have been executed to false.

Svelte If block

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}

Svelte If Block REPL

Svelte Else block

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}

Svelte Else block REPL

Svelte Else-If block

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}

Svelte Else-If block REPL

Conclusion

If / Else syntax makes it easy to write logic inside Svelte components as these are commonly used when it comes to real-world applications

About the Author

Sriram Thiagarajan

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.

Join our mailing list

We will reach out when exciting new posts are available. We won’t send you spam. Unsubscribe at any time.