Skip to content

Template Blocks

React renders conditionals and lists entirely in JavaScript: ternaries, &&, and .map() inside JSX. Svelte provides template block syntax — dedicated control-flow tags that live in the markup, closer to how HTML templating languages like Handlebars or Jinja work.

Conditionals: {#if} / {:else} vs JSX ternary

Section titled “Conditionals: {#if} / {:else} vs JSX ternary”
React
function Status({ loggedIn }) {
return (
<div>
{loggedIn
? <p>Welcome back!</p>
: <p>Please log in.</p>}
</div>
);
}
Svelte
<script>
let { loggedIn } = $props();
</script>
{#if loggedIn}
<p>Welcome back!</p>
{:else}
<p>Please log in.</p>
{/if}

You can also add {:else if condition} branches exactly like else if in JavaScript.

React
function FruitList({ fruits }) {
return (
<ul>
{fruits.map((fruit, i) => (
<li key={i}>{fruit}</li>
))}
</ul>
);
}
Svelte
<script>
let { fruits } = $props();
</script>
<ul>
{#each fruits as fruit, i (i)}
<li>{fruit}</li>
{/each}
</ul>

The (i) at the end is the keying expression — equivalent to React’s key prop. Use a stable unique ID when available (not the index).

React
function UserCard({ userId }) {
const [user, setUser] = React.useState(null);
React.useEffect(() => {
fetch('/api/users/' + userId)
.then(r => r.json())
.then(setUser);
}, [userId]);
if (!user) return <p>Loading...</p>;
return <p>{user.name}</p>;
}
Svelte
<script>
let { userId } = $props();
let promise = fetch('/api/users/' + userId).then(r => r.json());
</script>
{#await promise}
<p>Loading...</p>
{:then user}
<p>{user.name}</p>
{:catch error}
<p>Error: {error.message}</p>
{/await}
What is the Svelte 5 equivalent of React's array .map() for rendering a list?
How do you key list items in a Svelte {#each} block?
Which Svelte block handles a Promise with loading, success, and error states?
How do you add an else-if branch in a Svelte {#if} block?