Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Conditional Rendering with {#if} | Reactivity and User Interaction
Introduction to Svelte

Conditional Rendering with {#if}

Свайпніть щоб показати меню

Frontend applications often need to display different content depending on the current state of the application. For example, a website may show a loading message, an error message, or user content depending on available data.

Svelte handles this behavior using conditional rendering.

What Is Conditional Rendering?

Conditional rendering means displaying content only when certain conditions are true.

In Svelte, conditional rendering uses the {#if} block syntax.

Basic {#if} Example

Open App.svelte and add the following code:

<script>
  let isLoggedIn = true;
</script>

{#if isLoggedIn}
  <h2>Welcome back!</h2>
{/if}

The message only appears when the value of isLoggedIn is true.

If the value changes to false, the content disappears automatically.

Using {:else}

Svelte also supports alternative content using {:else}.

<script>
  let isLoggedIn = false;
</script>

{#if isLoggedIn}
  <h2>Welcome back!</h2>
{:else}
  <h2>Please sign in.</h2>
{/if}

Now the interface displays different content depending on the application state.

Why Conditional Rendering Matters

Common examples include:

  • Authentication states;
  • Loading indicators;
  • Error messages;
  • Empty states;
  • Notifications;
  • Dynamic menus.
question mark

What will happen if isLoggedIn is false in the following code?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 4

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 3. Розділ 4
some-alt