Svelte Routing with Page.js
Jscrambler
Posted on June 12, 2020
In this article, we'll learn about how to implement routing in our Svelte.js apps.
In a previous tutorial, we have created a simple news app that fetches data from a remote REST API and we even compared it with React.
Let's now see how to add routing to that Svelte app.
Prerequisites
In order to follow this tutorial, you should have:
- Familiarity with JavaScript alongside with HTML and CSS;
- Both Node 8+ and npm installed on your machine. You can use nvm (macOS/Linux) or nvm-windows to install and switch between Node versions in your system.
Initializing our Svelte App
Head over to your terminal and run the following command:
npm install -g degit
Next, initialize a new app using the following commands:
npx degit sveltejs/template sveltenewsapp
cd sveltenewsapp
npm install
npm run dev
You can access the app from the http://localhost:5000/
address.
Next, let's see how to implement routing in our Svelte application.
How to Add Routing to Svelte.js
You can add routing to your Svelte app using various ways such as:
- Using Sapper, a framework built on top of Svelte by the Svelte team;
- Use community packages like svelte-routing or Page.js.
We'll use Page.js to implement routing in this article. This seems to be a highly popular choice among Svelte developers mainly due to its high configurability.
Installing Page.js
We will get started by installing Page.js in our project.
Head back to your terminal, make sure you are inside the folder of your Svelte app and run the following command:
npm install page
Next, open the package.json
file and change:
"start": "sirv public"
To:
"start": "sirv public --single"
This will make sure we don't get any errors when navigating to routes from the browser's address bar.
Creating Components
Let's now create a few components in our application,
First, create a components/
folder in the src/
folder. Next, create two files, Home.svelte
and About.svelte
, inside the src/components/
folder.
Now, open the src/components/Home.svelte
and update it as follows:
<script>
import { onMount } from "svelte";
const apiKEY = "YOUR-API-KEY";
const dataUrl = `https://newsapi.org/v2/everything?q=javascript&sortBy=publishedAt&apiKey=${apiKEY}`;
let items = [];
const fetchData = async () => {
const response = await fetch(dataUrl);
const data = await response.json();
console.log(data);
items = data["articles"];
};
onMount(fetchData());
</script>
<div class="container">
{#each items as item}
<div class="card">
<img src="{item.urlToImage}">
<div class="card-body">
<h3>{item.title}</h3>
<p> {item.description} </p>
<a href="{item.url}">Read</a>
</div>
</div>
{/each}
</div>
<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>
You can get your own API key from the News API website.
For more details about this code, refer to the previous tutorial.
Next, open the src/components/About.svelte
file and update it as follows:
<script>
</script>
<div class="container">
This is a news app created with Svelte
</div>
<style>
</style>
Integrating Page.js with Svelte.js
Now, let's see how to use Page.js with Svelte.
Open the src/App.svelte
file and import the router
from the page
package, and also the two Home
and About
components:
<script>
import router from "page"
import Home from './components/Home.svelte'
import About from './components/About.svelte'
</script>
Next, define a page variable that will hold the matched component:
<script>
// [...]
let page
</script>
After that, define the routes of your application and call the start
method of the router to start watching the changes on the URL:
<script>
// [...]
router('/', () => page = Home)
router('/about', () => page = About)
router.start()
</script>
We created two routes for the Home
and About
components.
We passed, to the router
function, the path as the first property and an arrow function to assign the matched component to the page
variable as the second property. This will simply tell Page.js to watch for the changes on the URL in the browser and set the appropriate component as we specified.
Finally, we need to tell the router where to insert the matched component using the following code:
<h1>
Daily News
</h1>
<svelte:component this={page} />
This should be added after the closing </script>
tag.
You can now visit the /
and /about
paths to see the corresponding pages.
You can also use parameters with routes. For example, let’s suppose we want to be able to access a single article by its ID; you can do something like the following:
let params;
router('/article/:id', (ctx, next) => {
params = ctx.params
next()}, () => page = Article)
Where the ID is the parameter and the Article is a component that will be rendered when users visit routes such as /article/1
.
In the Article component, we can access the ID parameter using the following code:
<script>
import { onMount } from "svelte";
export let params;
const getID = async () => {
console.log(params.id);
};
onMount(getID());
</script>
Conclusion
In this article, we have implemented routing in our Svelte app using the Page.js library.
We have built this on top of our previous tutorial where we created a simple news application. Here, we refactored the app to have two pages routed using a client-side JavaScript router available from Page.js, which is a popular choice among the growing Svelte community.
Have you given Svelte a try yet? If not, it may be worth a go!
But regardless of the JavaScript framework you're using, you should always protect its source code to avoid reverse-engineering and code tampering. See our tutorials on protecting React, Angular, Vue, React Native, Ionic, and NativeScript.
Originally published on the Jscrambler Blog by Ahmed Bouchefra.
Posted on June 12, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.