What is Hash Routing in Svelte?

Ashutosh Kukreti

It's hard to imagine a web application without navigating the different URLs in the browser. In this article, we learn about the simple yet effective way of changing the routes in Svelte. It is Hash routing.

In the article, we create :

  • About
  • Contact url

We'll also add the NotFound page in case the url doesn't match with any of the routes.

Create About.svelte component

<br />
<br />
<hr/>

<p>I am about page </p>

And now add another component Contact.svelte

<br />
<br />
<hr/>
<p>I am contact</p>

And finally add NotFound.svelte

<br />
<br />
<hr/>
<strong>Page Not found</strong>

Whenever URL changes, the web browser emits a hashchange event. We need to listen to hashchange events and upload the relevant component.

Not in the App.svelte, under the script add routeChange() function. And import the About, Contact and NotFound component.

<script>
import About from "./components/About.svelte";
import NotFound from "./components/NotFound.svelte";
import Contact from "./components/Contact.svelte";

const routingMap = {
    '#about': About,
    '#contact': Contact
};

let page;

function routeChange() {
    page = routingMap[location.hash] || NotFound;
}
</script>

Whenever the url changes, routeChange() function is called. And now we need to add the window object of svelte.

<svelte:window on:hashchange={routeChange} /> And also for the testing purpose, we add the anchors links. So the complete App.svelte file looks like

<script>

	import About from "./components/About.svelte";
	import NotFound from "./components/NotFound.svelte";
	import Contact from "./components/Contact.svelte";

	const routingMap = {
		'#about': About,
		'#contact': Contact
	};

	let page;

	function routeChange() {
		page = routingMap[location.hash] || NotFound;
	}
</script>

/*
svelte:window is Svelte element supports the adding of event listeners 
of the window object.
*/

<svelte:window on:hashchange={routeChange} />

<nav>
	<a href="/#about" class:active={page === About}>About</a> &nbsp; &nbsp;
	<a href="/#contact" class:active={page === Contact} class="icon">
		Contact Us
	</a>

</nav>

<main>
    /*
    * Another svelte component that renders the page
    */
	<svelte:component this={page} />
</main>

Thats all for this article. See you in the next one.

Svelte3BeginnersJavaScript