Control Flow in Svelte: Using `#if`, `#else-if`, and `#else`
Introduction to Control Flow in Svelte
Welcome back! In the previous lesson, you learned how to use Svelte’s reactivity model with runes like $state and $derived to create dynamic and responsive components. Now, we’ll explore another essential feature of Svelte: control flow. Control flow allows you to conditionally render parts of your UI based on specific conditions, making your applications more interactive and user-friendly.
In this lesson, we’ll focus on three key control flow structures: #if, #else-if, and #else. These blocks enable you to show or hide content dynamically, depending on the state of your application. For example, you might want to display a welcome message only if a user is logged in or show different content based on their role.
To keep things simple, we’ll build on the reactivity concepts you’ve already learned, using $state to manage the conditions that control what gets rendered. Let’s dive in and see how these control flow blocks work in practice!
Understanding the `#if` Block
The #if block is the simplest form of control flow in Svelte. It allows you to conditionally render content based on a boolean expression. If the expression evaluates to true, the content inside the #if block is displayed; otherwise, it’s hidden.
Here’s a basic example:
In this example, the isVisible state variable controls whether the paragraph is displayed. Clicking the button toggles the value of isVisible, showing or hiding the message.
This is a simple yet powerful way to control what your users see based on the state of your application.
Adding `#else-if` and `#else` Blocks
While #if is great for simple conditions, you’ll often need to handle multiple conditions. This is where #else-if and #else come in. The #else-if block allows you to check additional conditions if the previous #if or #else-if block evaluates to false. The #else block provides a fallback for when none of the conditions are met.
Let’s look at an example where we display different messages based on a user’s role:
In this example, the message displayed depends on the value of userRole. If userRole is null, the #else block ensures a default message is shown. This structure makes it easy to handle complex logic while keeping your code clean and readable.
