Skip to main content

The <svelte:fragment> element allows you to place content in a named slot without wrapping it in a container DOM element.

In this exercise, we're making a Tic-Tac-Toe game. To form a grid, the <button> elements in App.svelte should be direct descendants of the <div class="board"> element in Board.svelte.

At the moment, it's horribly broken, because they're children of <div slot="game"> instead. Let's fix it:

App.svelte
<svelte:fragment slot="game">
	{#each squares as square, i}
		<button
			class="square"
			class:winning={winningLine?.includes(i)}
			disabled={square}
			on:click={() => {
				squares[i] = next;
				next = next === 'x' ? 'o' : 'x';
			}}
		>
			{square}
		</button>
	{/each}
</svelte:fragment>

Next: Module context

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
<script>
	import Board from './Board.svelte';
	import { getWinningLine } from './utils.js';
 
	let squares = Array(9).fill('');
	let next = 'x';
 
	$: winningLine = getWinningLine(squares);
</script>
 
<div class="container">
	<Board size={3}>
		<div slot="game">
			{#each squares as square, i}
				<button
					class="square"
					class:winning={winningLine?.includes(i)}
					disabled={square}
					on:click={() => {
						squares[i] = next;
						next = next === 'x' ? 'o' : 'x';
					}}
				>
					{square}
				</button>
			{/each}
		</div>
 
		<div slot="controls">
			<button on:click={() => {
				squares = Array(9).fill('');
				next = 'x';
			}}>
				Reset
			</button>
		</div>
	</Board>
</div>
 
<style>
	.container {
		display: flex;
		flex-direction: column;
		gap: 1em;
		align-items: center;
		justify-content: center;
		height: 100%;
		margin: 0 auto;
	}
 
	.square, .square:disabled {
		background: white;
		border-radius: 0;
		color: #222;
		opacity: 1;
		font-size: 2em;
		padding: 0;
	}
 
	.winning {
		font-weight: bold;
	}
 
	.container:has(.winning) .square:not(.winning) {
		color: #ccc;
	}
</style>
initialising