How to init Bootstrap Popover in Webpack Rails project

Viewed 222

So I followed the bootstrap doc on who to init the popover, but it doesn't work. It threw this error. How do I fix this?

Uncaught TypeError: bootstrap.Popover is not a constructor

These are the codes.

test_popover.html

  <button type="button" class="btn btn-lg btn-danger" data-bs-toggle="popover" title="Popover title" 
          data-bs-content="And here's some amazing content. It's very engaging. Right?">
    Click
  </button>

test_popover.js

  ...
  var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
  var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
    return new bootstrap.Popover(popoverTriggerEl)
  })

I have import the bootstrap in packs/application.js

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
    

// Import Bootstrap only ones that are used to reduce size
import 'bootstrap';
import '../javascripts/test_popover';
1 Answers

This is how I got it fixed. I import the Popover and changed from new bootstrap.Popover() to new Popover()

import Popover from 'bootstrap/js/dist/popover';

document.addEventListener("turbolinks:load", function() {    
  var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
  var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
    return new Popover(popoverTriggerEl)
  })
});
Related