Unlock the Power of Svelte: A Modern Frontend Library
The latest “State of JavaScript” survey reveals that Svelte is the frontend library to watch in 2020, thanks to its modern style and simplicity. As a modern reactive component framework, Svelte runs at build time, converting components into highly efficient imperative code that surgically updates the DOM.
Building a Simple App with Svelte and API
In this article, we’ll explore how Svelte consumes and renders data from an API by building a simple app. We’ll create a backend to store our data and then write our Svelte components. Assuming you have a basic understanding of JavaScript, CSS, Node.js, and Svelte, let’s dive in!
Setup and Installation
To get started, we’ll set up a working directory for our application using degit, a scaffolding tool to clone a Svelte template. Run the following command in your terminal:
npx degit sveltejs/template continent-app
Next, navigate into the newly created directory and install the dependencies:
cd continent-app
npm install
Create two component files, Continents
and Continent
, and start the app:
npm run dev
You should see the default landing page.
Building the API
Our API is a simple one that holds hardcoded information about the seven continents. Create a new folder api
in the app’s directory and install the required dependencies:
cd api
npm init -y
npm install express body-parser
Create a new file app.js
that will hold the simple backend:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const continents = [
{ name: 'Africa', population: 1234, countries: 56, area: 30000000 },
{ name: 'Asia', population: 4567, countries: 78, area: 44000000 },
//...
];
app.get('/api/continents', (req, res) => {
res.json(continents);
});
app.listen(8081, () => {
console.log('Server started on port 8081');
});
<code>
Start the backend with the command:
</code>
node app.js
``<code>
You should see a running message, and navigating to</code>localhost:8081` returns a list of continents and their data.
<strong>Writing the Svelte Components</strong>
Now that we have our backend up and running, let's write our Svelte components to retrieve and render the data. We'll write two components: <code>Continent</code> and <code>Continents</code>.
<strong>Continent Component</strong>
The <code>Continent</code> component renders the data of a continent passed as a prop to it from the <code>Continents</code> component.
```svelte
<script>
export let continent;
</script>
<div>
<h2>{continent.name}</h2>
Population: {continent.population}
Countries: {continent.countries}
Area: {continent.area} km²
</div>
<style>
/* Add some styling */<br />
</style>
Continents Component
The Continents
component retrieves the list of continents from the backend and renders them through the Continent
component.
<script>
import { onMount } from 'velte';
import Continent from './Continent.svelte';
let continents = [];
onMount(async () => {
const response = await fetch('/api/continents');
continents = await response.json();
});
</script>
{#if continents.length > 0}
{#each continents as continent}
{/each}
{:else}
Loading...
{/if}
<style>
/* Add some styling */<br />
</style>
Rendering the App
We’ve successfully written the components, and now it’s time to render the data via the app’s main component. Rewrite the App
component:
<script>
import Continents from './Continents.svelte';
</script>
<main>
</main><style>
/* Add some styling */<br />
</style>
<code>
Start the app with the command:
</code>
npm run dev
You should see the rendered data from the API.
What’s Next?
In this article, we’ve explored how to consume and render data from a backend in Svelte, define and export props, and pass props to components. We’ve also briefly looked at the onMount()
method. With Svelte’s built-in template system, building simple apps has never been easier. Happy coding!