Created
January 18, 2022 02:59
-
-
Save spaquet/1bdfef05161991878ed20eb7fde23548 to your computer and use it in GitHub Desktop.
Rails Popper Stimulus Controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Controller } from "@hotwired/stimulus"; | |
import { createPopper } from "@popperjs/core"; | |
// Connects to data-controller="popper" | |
export default class extends Controller { | |
static targets = ["element", "tooltip"]; | |
static values = { | |
placement: { type: String, default: "top" }, | |
offset: { type: Array, default: [0, 8] }, | |
}; | |
connect() { | |
// Create a new Popper instance | |
this.popperInstance = createPopper(this.elementTarget, this.tooltipTarget, { | |
placement: this.placementValue, | |
modifiers: [ | |
{ | |
name: "offset", | |
options: { | |
offset: this.offsetValue, | |
}, | |
}, | |
], | |
}); | |
} | |
show(event) { | |
this.tooltipTarget.setAttribute("data-show", ""); | |
// We need to tell Popper to update the tooltip position | |
// after we show the tooltip, otherwise it will be incorrect | |
this.popperInstance.update(); | |
} | |
hide(event) { | |
this.tooltipTarget.removeAttribute("data-show"); | |
} | |
// Destroy the Popper instance | |
disconnect() { | |
if (this.popperInstance) { | |
this.popperInstance.destroy(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment