Svelte : fetch image source

Stephen Lai
2 min readApr 19, 2020

Svelte has an online editor so that you don’t need to open VSCode to develop your project which is pretty handy. Today we are gonna get random image from picsum.photos and display in our page.

First create RandomImage.svelte which is our child component. In script section we declare src , alt variables for img tag. Then we use fetch() api to get the image source

<script>
let src = 'is loading...'
let alt = 'Random Image'
let API = 'https://picsum.photos/300'
// use promise to get image source with fetch api
fetch(API).then(res => res.url)
// If you prefer async/await method, you can do that also
async function loadImage() {
const res = await fetch(API)
src = await res.url
}
loadImage()</script>

In html section we put a h3 tag indicating the image source and display the image with img tag

<h3>
The src is {src}
</h3>
// If attribute and value are the same name, we can use shorthand expression like {src} {alt}
<img {src} {alt} />

In our App.svelte , we import RandomImage.svelte and display the image with RandomImage component. We use display:gridto make the layout look organized

<script>
import RandomImage from './RandomImage.svelte'
</script>
<!-- we can display as many images as we want -->
<RandomImage />
<RandomImage />
<RandomImage />
<style>
.box {
display: grid;
grid-template-columns: repeat(2, 1fr);
}
</style>

The results

And that’s it. You can also download the project to your local drive and start the local server to run and test it, ain’t it amazing !!!

Svelte Rocks !!!

--

--