Skip to main content

Components can pass data back to their slotted content via slot props. In this app, we have a list of named CSS colours. Typing into the <input> will filter the list.

Right now every row is showing AliceBlue, and as lovely a colour as it is, that's not what we want.

Open FilterableList.svelte. The <slot> is being rendered for each filtered item in the list. Pass the data into the slot:

FilterableList.svelte
<div class="content">
	{#each data.filter(matches) as item}
		<slot {item} />
	{/each}
</div>

(As in other contexts, {item} is shorthand for item={item}.)

Then, on the other side, expose the data to the slotted content with the let: directive:

App.svelte
<FilterableList
	data={colors}
	field="name"
	let:item={row}
>
	<div class="row">
		<span class="color" style="background-color: {row.hex}" />
		<span class="name">{row.name}</span>
		<span class="hex">{row.hex}</span>
		<span class="rgb">{row.rgb}</span>
		<span class="hsl">{row.hsl}</span>
	</div>
</FilterableList>

Finally, get rid of the placeholder variable, which we no longer need:

App.svelte
<script>
	import FilterableList from './FilterableList.svelte';
	import { colors } from './colors.js';

	let row = colors[0];
</script>

Named slots can also have props; use the let directive on an element with a slot="..." attribute, instead of on the component itself.

Next: Checking for slot content

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<script>
	import FilterableList from './FilterableList.svelte';
	import { colors } from './colors.js';
 
	let row = colors[0];
</script>
 
<FilterableList
	data={colors}
	field="name"
>
	<header slot="header" class="row">
		<span class="color" />
		<span class="name">name</span>
		<span class="hex">hex</span>
		<span class="rgb">rgb</span>
		<span class="hsl">hsl</span>
	</header>
 
	<div class="row">
		<span class="color" style="background-color: {row.hex}" />
		<span class="name">{row.name}</span>
		<span class="hex">{row.hex}</span>
		<span class="rgb">{row.rgb}</span>
		<span class="hsl">{row.hsl}</span>
	</div>
</FilterableList>
 
<style>
	.row {
		display: grid;
		align-items: center;
		grid-template-columns: 2em 4fr 3fr;
		gap: 1em;
		padding: 0.1em;
		background: var(--bg-1);
		border-radius: 0.2em;
	}
 
	header {
		font-weight: bold;
	}
 
	.row:not(header):hover {
		background: var(--bg-2);
	}
 
	.color {
		aspect-ratio: 1;
		height: 100%;
		border-radius: 0.1em;
	}
 
	.rgb, .hsl {
		display: none;
	}
 
	@media (min-width: 40rem) {
		.row {
			grid-template-columns: 2em 4fr 3fr 3fr;
		}
 
		.rgb {
			display: block;
		}
	}
 
	@media (min-width: 60rem) {
		.row {
			grid-template-columns: 2em 4fr 3fr 3fr 3fr;
		}
 
		.hsl {
			display: block;
		}
	}
</style>
initialising