DEV Community

M. E. Patterson
M. E. Patterson

Posted on

Using Tippy.js with StimulusReflex and CableReady

So you've got a killer StimulusReflex-based Rails app going, and you're using CableReady all over the place, and the DOM is morphing, and everything is going great! Now, you're ready to start adding in some tooltips here and there to polish up your user experience. Enter Tippy.js for much success.

At first, you just add an event handler listening to turbolinks reloads and have it initialize all the tippy elements on the page. And that works great...

...until you use a Reflex to morph the DOM. Ack! Elements that were morphed that were supposed to have Tippy(s) now... don't.

Of course, this makes sense. StimulusReflex, via CableReady, is morphing the DOM; it's not a Turbolinks load. So we'll need to change that.

First, get rid of the turbolinks event handler. We're just going to do this with Stimulus and a cable-ready:after-morph event handler:

// tippy_controller.js

import { Controller } from "stimulus";
import tippy from "tippy.js";

export default class extends Controller {
  initialize() {
    document.addEventListener(
      "cable-ready:after-morph",
      this.initializeTippys.bind(this),
      true
    );
  }

  connect() {
    this.initializeTippys();
  }

  disconnect() {
    this.destroyTippys();
  }

  initializeTippys() {
    this.destroyTippys();
    tippy(document.querySelectorAll("[data-tippy-content]"));
  }

  destroyTippys() {
    let tips = document.querySelectorAll("[data-tippy-content]");
    tips.forEach((e) => {
      if (e._tippy) e._tippy.destroy();
    });
  }
}

Cool. Now that that's out of the way, you just need to add data-controller="tippy" to the right element(s) in your HTML. Personally, I just add it to the BODY tag so I can always make tooltips anywhere, any time.

Enjoy!

(let me know in the comments if there's an issue with this approach, or you have a better way, but it worked for me!)

Top comments (1)

Collapse
 
leastbad profile image
leastbad • Edited
  1. I know this is obnoxious but... don't you mean tippies

  2. You should take something like stimulus-shortcut, replace all of the bits and bobs, and then publish this as stimulus-tippies