How to Build a News App with Svelte

How to Build a News App with Svelte
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.

Next, let’s add the following HTML markup to create the UI of our application and display the news data:

<h1>
    <img src="https://dailyplanetdc.files.wordpress.com/2018/12/cropped-daily-planet-logo.jpg?w=656&h=146" />
    <p class="about">
            The Daily Planet is where heroes are born and the story continues. We are proud to report on the planet, daily.
    </p>
</h1>

<div class="container">

        {#each articles as article}
            <div class="card">
                <img src="{article.urlToImage}">
                <div class="card-body">
                    <h3>{article.title}</h3>
                    <p> {article.description} </p>
                    <a href="{article.url}">Read story</a>
                </div>
            </div>
        {/each}

</div>

We use the each block to loop over the news articles and we display the title, description, url and urlToImage of each article.

The daily planet logo and the headline are borrowed from this nonprofit news organization that’s inspired by DC Comics.

We’ll make use of Kalam, a handwritten font available from Google fonts, so open the public/index.html file and add the following tag:

<link  href="https://fonts.googleapis.com/css?family=Kalam"  rel="stylesheet">

Next, go back to the App.svelte file and add the following styles:

<style>
h1 {
    color: purple;
    font-family: 'kalam';
}

.container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(305px, 1fr));
    grid-gap: 15px;
}

.container > .card img {
    max-width: 100%;
}
</style>

This is a screenshot of our daily news app:

A screenshot of our daily news app

Building for Production

After developing your application, you can create the production bundles by running the build command in your terminal:

npm run build

The command will produce a minified and production-ready bundle that you can host on your preferred hosting server.

Let’s now host the application using ZEIT Now.

ZEIT Now is a cloud platform for websites and serverless functions that you can use to deploy your projects to a .now.sh or personal domain.

Go back to your terminal and run the following command to install Now CLI:

npm  install -g now

Next, navigate to the public folder and run the now command:

cd public
now

That’s it! Your application will be deployed to the cloud. In our case, it’s available from public-kyqab3g5j.now.sh.

You can find the source code of this application from this GitHub repository.

Conclusion

In this tutorial, we built a simple news app using Svelte. We also saw what Svelte is and how to create a Svelte project using the degit tool from npm.

You can refer to the official docs for a detailed tutorial to learn about every Svelte feature.

Recommended Reading

The Svelte 3 Quick Tutorial

Learn Svelte 3.0 - Svelte Tutorial for Beginners

Build A Simple ToDo App using Svelte and Cosmic JS

Suggest:

Top 4 Programming Languages to Learn In 2019

Top 4 Programming Languages to Learn in 2019 to Get a Job

What To Learn To Become a Python Backend Developer

Dart Programming Tutorial - Full Course

Introduction to Functional Programming in Python

There Is No Best Programming Language