What does Svelte look like? Basic Svelte Code Examples

What does Svelte look like? Basic Svelte Code Examples

I created this post for future reference, with my own examples as I was following along some basic Svelte tutorials that can be found here ( svelte.dev/tutorial )

Svelt script for first letter uppercase/capital

<!-- App.svelte -->
<script>
let name = 'hashnode';

function capitalizeFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}
</script>

<h1>Hello {capitalizeFirstLetter(name)}!</h1>

image.png


Dynamic attributes example with a random image

<!-- App.svelte -->
<script>
    let src = 'https://picsum.photos/200/200';
    let alt = 'Some random image';
</script>
<h1>Image 1</h1>
<img alt={alt} src={src}>
<h1>Image 2</h1>
<img {alt} {src}>

image.png


Adding CSS to a component

<!-- App.svelte -->
<style>
    span {
        color: blue;
        font-family: sans-serif;
    }
</style>

<h1>Hi <span>Hashnode</span>!</h1>

image.png


Nested components with scoped styles

<!-- App.svelte -->
<script>
    import Nested from './Nested.svelte';
</script>

<style>
    span {
        color: blue;
        font-family: sans-serif;
    }
</style>

<h1>Hi <span>Hashnode</span>!</h1>
<Nested/>
<!-- Nested.svelte -->
<style>
    span {
        color: green;
    }
</style>
<h2>Hello fellow <span>reader</span>!</h2>

image.png


Nested components with global styles

<!-- App.svelte -->
<script>
    import Nested from './Nested.svelte';
</script>

<style>
    :global(span) {
        color: blue;
        font-family: sans-serif;
    }
</style>

<h1>Hi <span>Hashnode</span>!</h1>
<Nested/>
<!-- Nested.svelte -->
<h2>Hello fellow <span>reader</span>!</h2>

image.png


HTML tags / Remember to sanitize them b4 displaying them

<!-- App.svelte -->
<script>
    let string = `Withount html tag <strong>HTML CONTENT!!!</strong>`;
    let string2 = `With html tag <strong>HTML CONTENT!!!</strong>`;
</script>

<p>{string}</p>
<p>{@html string2}</p> <!-- this still needs sanitization -->

image.png