How to Build a News App with Svelte
Original Source: https://www.sitepoint.com/svelte-news-app-build/?utm_source=rss
Svelte is a new JavaScript UI library that’s similar in many ways to modern UI libraries like React. One important difference is that it doesn’t use the concept of a virtual DOM.
In this tutorial, we’ll be introducing Svelte by building a news application inspired by the Daily Planet, a fictional newspaper from the Superman world.
About Svelte
Svelte makes use of a new approach to building users interfaces. Instead of doing the necessary work in the browser, Svelte shifts that work to a compile-time phase that happens on the development machine when you’re building your app.
In a nutshell, this is how Svelte works (as stated in the official blog):
Svelte runs at build time, converting your components into highly efficient imperative code that surgically updates the DOM. As a result, you’re able to write ambitious applications with excellent performance characteristics.
Svelte is faster than the most powerful frameworks (React, Vue and Angular) because it doesn’t use a virtual DOM and surgically updates only the parts that change.
We’ll be learning about the basic concepts like Svelte components and how to fetch and iterate over arrays of data. We’ll also learn how to initialize a Svelte project, run a local development server and build the final bundle.
Prerequisites
You need to have a few prerequisites, so you can follow this tutorial comfortably, such as:
Familiarity with HTML, CSS, and JavaScript (ES6+),
Node.js and npm installed on your development machine.
Node.js can be easily installed from the official website or you can also use NVM for easily installing and managing multiple versions of Node in your system.
We’ll be using a JSON API as a source of the news for our app, so you need to get an API key by simply creating an account for free and taking note of your API key.
Getting Started
Now, let’s start building our Daily Planet news application by using the degit tool for generating Svelte projects.
You can either install degit globally on your system or use the npx tool to execute it from npm. Open a new terminal and run the following command:
npx degit sveltejs/template dailyplanetnews
Next, navigate inside your project’s folder and run the development server using the following commands:
cd dailyplanetnews
npm run dev
Your dev server will be listening from the http://localhost:5000 address. If you do any changes, they’ll be rebuilt and live-reloaded into your running app.
Open the main.js file of your project, and you should find the following code:
import App from ‘./App.svelte’;
const app = new App({
target: document.body,
props: {
name: ‘world’
}
});
export default app;
This is where the Svelte app is bootstrapped by creating and exporting an instance of the root component, conventionally called App. The component takes an object with a target and props attributes.
The target contains the DOM element where the component will be mounted, and props contains the properties that we want to pass to the App component. In this case, it’s just a name with the world value.
Open the App.svelte file, and you should find the following code:
<script>
export let name;
</script>
<style>
h1 {
color: purple;
}
</style>
<h1>Hello {name}!</h1>
This is the root component of our application. All the other components will be children of App.
Components in Svelte use the .svelte extension for source files, which contain all the JavaScript, styles and markup for a component.
The export let name; syntax creates a component prop called name. We use variable interpolation—{…}—to display the value passed via the name prop.
You can simply use plain old JavaScript, CSS, and HTML that you are familiar with to create Svelte components. Svelte also adds some template syntax to HTML for variable interpolation and looping through lists of data, etc.
Since this is a small app, we can simply implement the required functionality in the App component.
In the <script> tag, import the onMount() method from “svelte” and define the API_KEY, articles, and URL variables which will hold the news API key, the fetched news articles and the endpoint that provides data:
<script>
export let name;
import { onMount } from “svelte”;
const API_KEY = “<YOUR_API_KEY_HERE>”;
const URL = `https://newsapi.org/v2/everything?q=comics&sortBy=publishedAt&apiKey=${API_KEY}`;
let articles = [];
</script>
onMount is a lifecycle method. Here’s what the official tutorial says about that:
Every component has a lifecycle that starts when it is created and ends when it is destroyed. There are a handful of functions that allow you to run code at key moments during that lifecycle. The one you’ll use most frequently is onMount, which runs after the component is first rendered to the DOM.
Next, let’s use the fetch API to fetch data from the news endpoint and store the articles in the articles variable when the component is mounted in the DOM:
<script>
// […]
onMount(async function() {
const response = await fetch(URL);
const json = await response.json();
articles = json[“articles”];
});
</script>
Since the fetch() method returns a JavaScript Promise, we can use the async/await syntax to make the code look synchronous and eliminate callbacks.
The post How to Build a News App with Svelte appeared first on SitePoint.
Leave a Reply
Want to join the discussion?Feel free to contribute!