Svelte logo

Svelte by Example: Actions

Actions are functions that bind to the lifecycle of a single element. They're especially useful to integrate Svelte with third-party libraries.

In this example, we'll use an action to bind a third-party datepicker component to an input.

An action is a function that receives an HTML element and an optional value. When the element is mounted, the action will run.

Return an update function to listen for changes of the action value.

Return a destroy function to clean up when the element is removed.

Actions are bound to an element with the use: directive.

Datepicker.svelte
<script>
export let minDate;

function datepicker(element, { minDate }) {
  const pickaday = new Pikaday({
    field: element,
    minDate,
  });

  return {
    update({ minDate }) {
      pickaday.setMinDate(minDate);
    },
    destroy() {
      pickaday.destroy();
    },
  };
}
</script>

<input use:datepicker={{ minDate, maxDate }} />