svelte-popperjs

Popper for Svelte with actions, no wrapper components required!

Usage no npm install needed!

<script type="module">
  import sveltePopperjs from 'https://cdn.skypack.dev/svelte-popperjs';
</script>

README

svelte-popperjs-banner

svelte-popperjs

npm version npm downloads license build coverage size

Popper for Svelte with actions, no wrapper components or component bindings required!

Other Popper libraries for Svelte (including the official @popperjs/svelte library) use a wrapper component that takes the required DOM elements as props. Not only does this require multiple bind:this, you also have to pollute your script tag with multiple DOM references.

We can do better with Svelte actions!

Installation

$ npm i -D svelte-popperjs

Since Svelte automatically bundles all required dependencies, you only need to install this package as a dev dependency with the -D flag.

Usage

createPopperActions takes an optional options object for configuring the popper instance, and returns a pair of actions to be used on the reference and popper elements.

The content action also takes an options object for updating the options of the popper instance.

Example

A Svelte version of the standard tutorial.

<script>
  import { createPopperActions } from 'svelte-popperjs';
  const [popperRef, popperContent] = createPopperActions();
  const popperOptions = {
    modifiers: [
      { name: 'offset', options: { offset: [0, 8] } }
    ],
  };

  let showTooltip = false;
</script>

<button
  use:popperRef
  on:mouseenter={() => showTooltip = true}
  on:mouseleave={() => showTooltip = false}
>
  My button
</button>
{#if showTooltip}
  <div id="tooltip" use:popperContent={popperOptions}>
    My tooltip
    <div id="arrow" data-popper-arrow />
  </div>
{/if}

API

Setting popper options

Popper options can be set statically when creating the popper actions, or dynamically on the content action.

If both are set, then the dynamic options will be merged with the initial options.

<script>
  // set once and no longer updated
  const [popperRef, popperContent] = createPopperActions(initOptions);
</script>

<!-- will be merged with initOptions -->
<div use:popperContent={dynamicOptions}/>

Accessing the Popper instance

If access is needed to the raw Popper instance created by the actions, you can reference the third element returned by createPopperActions. The third element is a function that will return the current Popper instance used by the actions.

Using the raw Popper instance to manually recompute the popper's position.

<script>
  import { createPopperActions } from 'svelte-popperjs';
  const [popperRef, popperContent, getInstance] = createPopperActions();

  async function refreshTooltip() {
    const newState = await getInstance().update();
  }
</script>