Once you have data, you must show the right state. We'll use conditionals and loops to build a familiar school-service UI.
Key terms
- Conditional rendering: Showing an element only when a state matches, implemented via
{#if}blocks. - List rendering: Repeating cards or items by looping over an array via
{#each}. key: The identifier in{#each item as thing (thing.id)}that keeps updates stable when order changes.- Empty state: The friendly message or button that appears when data is missing so users stay informed.
Core ideas
Conditional rendering displays UI only when context requires it, preventing mixed messages. List rendering turns arrays into repeated markup, and adding a key reduces flicker when entries change. Defining loading, empty, and data states in order keeps a page steady.
Code example
Let's create a commuter bus widget. A single section handles loading text, empty guidance, and the arrival list.
<script>
export let arrivals = [];
export let loading = true;
</script>
<section>
{#if loading}
<p>Fetching stop info…</p>
{:else if arrivals.length === 0}
<p>Check again in a moment.</p>
{:else}
<ul>
{#each arrivals as bus (bus.id)}
<li>
<strong>{bus.route}</strong> – arriving in {bus.remain} minutes
</li>
{/each}
</ul>
{/if}
</section>
When arrivals is empty you show the hint, otherwise you loop and render each item with bus.id as the key. This same pattern powers allergy tables, attendee lists, and announcement feeds.
Why it matters
Real services bounce between states. Slow data needs a loading line; missing data needs a retry nudge. Student dashboards obey the same rules. Mastering {#if} paired with {#each} lets you map server responses cleanly, so debugging goes faster later.
Practice
- Follow along: recreate the bus widget and toggle
loadingthrough all three states. - Extend: add a button in the empty state or color code each
arrivalsentry. - Debug: if messages overlap, check the closing tags and
arrivals.lengthcalculation. - Done when: switching array values produces the loading, empty, and list states in order.
Wrap-up
Combining conditionals and loops keeps state-driven UI flows natural. Next we'll bind inputs directly to state with bind:.
💬 댓글
이 글에 대한 의견을 남겨주세요