Bernardo Dal Corno
Bernardo Dal Corno

Reputation: 2088

Is it possible to create custom directives in svelte?

I know there are slots and some discussion about slots without DOM elements. What about custom directives? (That is, special "atributes" that will modify the behavior of a component/DOM element)

Upvotes: 9

Views: 3030

Answers (2)

parker_codes
parker_codes

Reputation: 3397

There are no custom directives just yet like you might find in Vue, but you can certainly bind actions to child elements with use:something. See the docs here. You can also find an official example here.

Here's a small example:

<button on:click={doSomething} use:tooltip={calculatedTooltip}>
    Click Me
</button>

Upvotes: 9

Yulian
Yulian

Reputation: 6759

Coming from an Angular background, I wondered the same. I was happy to see there's something similar in Svelte thanks to GoogleMac's answer.

If you are used to Angular, you'd probably be looking for event dispatches too (@Output in Angular). It seems like there's not such a concept in Svelte's actions but you can make use of parameters. Here's an example:

// outside-click.js => Action
export function outsideClick(node, onOutsideClick) {
  //                               ^^^^^^^^^^^^^^ parameter
  function handleClick ({ target }) {
    const clickedOutside = !node.contains(target);

    if (clickedOutside) {
      onOutsideClick();
    }
  }

  window.addEventListener('click', handleClick);

  return {
    destroy () {
      window.removeEventListener('click', handleClick);
    }
  };
}
// MyComponent.svelte => component
<script>
  function hideMenu() {
    // hide menu logic
  }
</script>

<div use:outsideClick={hideMenu} class="menu">
  <!-- Menu that has to be closed when clicking outside of it -->
</div>

Hope this would help someone.

Upvotes: 1

Related Questions