Skip to main content

When building user interfaces you’ll often find yourself working with lists of data. In this exercise, we’ve repeated the <button> markup multiple times — changing the colour each time — but there’s still more to add.

Instead of laboriously copying, pasting and editing, we can get rid of all but the first button, then use an each block:

App
<div>
	{#each colors as color}
		<button
			style="background: red"
			aria-label="red"
			aria-current={selected === 'red'}
			onclick={() => selected = 'red'}
		></button>
	{/each}
</div>

The expression (colors, in this case) can be any iterable or array-like object — in other words, anything that works with Array.from.

Now we need to use the color variable in place of "red":

App
<div>
	{#each colors as color}
		<button
			style="background: {color}"
			aria-label={color}
			aria-current={selected === color}
			onclick={() => selected = color}
		></button>
	{/each}
</div>

You can get the current index as a second argument, like so:

App
<div>
	{#each colors as color, i}
		<button
			style="background: {color}"
			aria-label={color}
			aria-current={selected === color}
			onclick={() => selected = color}
		>{i + 1}</button>
	{/each}
</div>

Edit this page on GitHub

<script>
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
let selected = $state(colors[0]);
</script>

<h1 style="color: {selected}">Pick a colour</h1>

<div>
<button
style="background: red"
aria-label="red"
aria-current={selected === 'red'}
onclick={() => selected = 'red'}
></button>

<button
style="background: orange"
aria-label="orange"
aria-current={selected === 'orange'}
onclick={() => selected = 'orange'}
></button>

<button
style="background: yellow"
aria-label="yellow"
aria-current={selected === 'yellow'}
onclick={() => selected = 'yellow'}
></button>

<!-- TODO add the rest of the colours -->
<button></button>
<button></button>
<button></button>
<button></button>
</div>

<style>
h1 {
transition: color 0.2s;
}

div {
display: grid;
grid-template-columns: repeat(7, 1fr);
grid-gap: 5px;
max-width: 400px;
}

button {
aspect-ratio: 1;
border-radius: 50%;
background: var(--color, #fff);
transform: translate(-2px,-2px);
filter: drop-shadow(2px 2px 3px rgba(0,0,0,0.2));
transition: all 0.1s;
}

button[aria-current="true"] {
transform: none;
filter: none;
box-shadow: inset 3px 3px 4px rgba(0,0,0,0.2);
}
</style>