Build a tabs component that displays one panel of content at a time depending on the active tab element. Some HTML is provided for you as example content.
ids, data attributes, replacing some tags, etc.) and use client-side rendering instead.1<script>2 export let items;3 export let defaultValue = undefined;4 let value = defaultValue ?? items[0].value;5</script>67<div class="tabs">8 <div class="tabs-list">9 {#each items as item (item.value)}10 <button11 type="button"12 class:tabs-list-item--active={item.value === value}13 class="tabs-list-item"14 on:click={() => (value = item.value)}>15 {item.label}16 </button>17 {/each}18 </div>19 {#each items as item (item.value)}20 <div hidden={item.value !== value}>{item.panel}</div>21 {/each}22</div>2324<style>25 .tabs {26 display: flex;27 flex-direction: column;28 gap: 8px;29 }3031 .tabs-list {32 display: flex;33 gap: 6px;34 }3536 .tabs-list-item {37 --active-color: blueviolet;38 background: none;39 border: 1px solid #000;40 border-radius: 4px;41 cursor: pointer;42 padding: 6px 10px;43 }4445 .tabs-list-item:hover {46 border-color: var(--active-color);47 color: var(--active-color);48 }4950 .tabs-list-item--active {51 background: var(--active-color);52 border-color: var(--active-color);53 color: #fff;54 }55</style>
The active item is a local variable initialized from defaultValue or the first item. An {#each} block renders keyed buttons and panels, while class: and hidden directives derive the presentation from that one value.
Each component instance owns its state, so multiple tab sets remain independent.
Accessibility is an important factor for making good Tabs components. The ARIA Authoring Practices Guide for Tabs has a long list of guidelines for the ARIA roles, states, and properties to add to the various elements of a tab. Tabs II and Tabs III will focus on improving the accessibility of the Tabs component.
console.log() statements will appear here.