Skip to main content

Since the two conditions — if user.loggedIn and if !user.loggedIn — are mutually exclusive, we can simplify this component slightly by using an else block:

{#if user.loggedIn}
	<button on:click={toggle}> Log out </button>
{:else}
	<button on:click={toggle}> Log in </button>
{/if}

A # character always indicates a block opening tag. A / character always indicates a block closing tag. A : character, as in {:else}, indicates a block continuation tag. Don't worry — you've already learned almost all the syntax Svelte adds to HTML.

App.svelte
<script>
let user = { loggedIn: false };

function toggle() {
user.loggedIn = !user.loggedIn;
}
</script>

{#if user.loggedIn}
<button on:click={toggle}> Log out </button>
{/if}

{#if !user.loggedIn}
<button on:click={toggle}> Log in </button>
{/if}

/* App.svelte generated by Svelte v4.2.19 */
import {
SvelteComponent,
detach,
element,
empty,
init,
insert,
listen,
noop,
safe_not_equal,
space
} from "svelte/internal";

import "svelte/internal/disclose-version";

function create_if_block_1(ctx) {
let button;
let mounted;
let dispose;

return {
c() {
button = element("button");
button.textContent = "Log out";
},
m(target, anchor) {
insert(target, button, anchor);
result = svelte.compile(source, {
generate:
css:
});
/* Add a <style> tag to see compiled CSS */