SziaTech
Technology

The Power of Svelte Actions

Attila Buturla
#webdev#svelte#frontend

Introduction

Svelte actions are a powerful and flexible feature that allows developers to interact directly with the DOM in a Svelte application. Unlike traditional event handlers, Svelte actions provide a way to encapsulate imperative, non-declarative behavior in a reusable manner. An action in Svelte is essentially a function that receives the DOM element associated with a component and can perform various tasks such as manipulating the DOM, adding event listeners, or integrating with third-party libraries. This feature enables developers to seamlessly incorporate dynamic behavior into their applications with concise and maintainable code. Svelte actions contribute to the framework’s philosophy of simplicity and efficiency, empowering developers to efficiently manage side effects while keeping their codebase clean and expressive.

Simple Example

To help illustrate actions in … action, here’s a simple example:

<script>
	function colorMe(node){
		node.style.backgroundColor = '#D8BFD8';
	}
</script>

<p use:colorMe>Hey down there! Could you give us a hand with this?</p>

First, we define a function that takes a single parameter. The function could be named anything, although it’s always good to provide a meaningful name. As you can see the parameter, which again can be named anything, is a reference to a DOM element. In this case we simply change the background color of the element to that of a light violet.

Then, in our template, we apply the action to an element, in this case a P tag, by using the use:<actionName> syntax. The end result is a paragraph of text with a violet background color. We can apply this aciton to any valid HTML element that supports the backgroundColor style.

This is a somewhat silly example, as there’s better ways to set the background color of elements, but it does illustrate how simple it is to create actions. Let’s look at another example.

Example 2

Here’s a more sophisticated, and perhaps slightly more realistic example of a Svelte action. This time we define an aciton named typeAhead. It listens for the keyup event, and if text has been entered, it tries to find a match in the imported fruits array. The key thing to note is that while we could easily create a type ahead component, this action essentially has the behavior of a component, but does not include any of the UI details. In this case we could reuse this action logic several places, and different consumers could implement the UI of the type ahead very differently.

<script>
	import { fruits }  from './fruits';

	let suggestions = '';
	let searchText = '';

	function typeAhead(node) {
		node.addEventListener('keyup', () => {
			if(searchText.length === 0){
				suggestions = '';
				return;
			}

			suggestions = fruits.filter(fruit => fruit.startsWith(searchText));
		});
	}
</script>

<div use:typeAhead>
	Fruit:
	<input type="text" bind:value={searchText}>
	<p>{suggestions}</p>
</div>

The sweet spot of actions, is that they allow you to reuse event listener and custom event logic. It sits in between the extremes of having a fullblown component, or just a pure vanilla JavaScript function. Again, this example is a little bit contrived, but helps demonstrate the flexiblity of actions.

The Real World

The two above examples illustrate how easy actions are to implement, and give an idea of how best to use them. The possible use cases are vast and lend themselves to quite a bit of creativity. Some other examples of uses for actions include the integration of 3rd party libraries that rely on DOM manipulation, the closing of modals when someone clicks outside of the modal area, or even scrolling to a specific DOM element, just to name a few.

Conclusion

The verstility of actions empower developers to seamlessly integrate animations, manage input focus, incorporate third-party libraries, and craft custom behaviors with unparalleled ease. Svelte’s commitment to simplicity and reactivity is exemplified through actions, enabling the creation of highly interactive and engaging web applications. Actions are a powerful tool, unlocking new possibilities and streamlining the way we build modern, responsive, and user-friendly interfaces.

← Back to Blog