In Svelte, an application is composed from one or more components. A component is a reusable self-contained block of code that encapsulates HTML, CSS and JavaScript that belong together, written into a .svelte
file.
Adding data
A component that just renders some static markup isn't very interesting. Let's add some data.
First, add a script tag to your component and declare a name variable. Then, we can refer to name in the markup. Inside the curly braces, we can put any JavaScript we want.
<script>
let name = 'Svelte';
</script>
<h1>Hello {name.toUpperCase()}!</h1>
Dynamic attributes
Just like you can use curly braces to control text, you can use them to control element attributes.
<script>
let src = '/image.gif';
let name = 'Rick Astley';
</script>
<img src={src} alt="{name} dances." />
Shorthand attributes
It's not uncommon to have an attribute where the name and value are the same, like src={src}. Svelte gives us a convenient shorthand for these cases:
<img {src} alt="{name} dances." />
Styling
Just like in HTML, you can add a <style>
tag to your component. Let's add some styles to the <p>
element:
<p>This is a paragraph.</p>
<style>
p {
color: goldenrod;
font-family: 'Comic Sans MS', cursive;
font-size: 2em;
}
</style>
Importantly, these rules are scoped to the component. You won't accidentally change the style of <p>
elements elsewhere in your app, as we'll see in the next step.
Nested components
It would be impractical to put your entire app in a single component. Instead, we can import components from other files and include them in our markup.
App.svelte
<script>
import Nested from './Nested.svelte';
</script>
<p>This is a paragraph.</p>
<Nested />
<style>
p {
color: goldenrod;
font-family: 'Comic Sans MS', cursive;
font-size: 2em;
}
</style>
Nested.svelte
<p>This is another paragraph.</p>
Notice that even though Nested.svelte
has a <p>
element, the styles from App.svelte
don't leak in. Also component names are always capitalised, to distinguish them from HTML elements.
HTML tags
Ordinarily, strings are inserted as plain text, meaning that characters like <
and >
have no special meaning. But sometimes you need to render HTML directly into a component. In Svelte, you do this with the special {@html ...}
tag:
<script>
let string = `this string contains some <strong>HTML!!!</strong>`;
</script>
<p>{@html string}</p>