reactjsdomreact-bootstrapvirtual-dombootstrap-5

How can i use Bootstrap 5 Popover in react.js component?


I am using Bootstrap 5 by CDN in react. I have one component that will be using the Popover in one of the react components. So, as per the documentation, it says "You must include popper.min.js before bootstrap.js or use bootstrap.bundle.min.js / bootstrap.bundle.js which contains Popper in order for popovers to work!"

And also to initialize all popovers on a page use the given javascript code:

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

But I am unable to use it in useEffect in my react component because it is returning the "bootstrap.Popover(popoverTriggerEl)" object which is undefined in my react component.

Please if anyone could guide me in this?


Solution

  • Now that Bootstrap 5 is modular, you can import components, or reference them directly from bootstrap...

    var popover = new bootstrap.Popover(document.querySelector('#myButton'), options)
    

    So to use it with React useEffect hook you could do something like this...

    function PopoverDemo() {
      const popoverRef = useRef()
      useEffect(() => {
        var popover = new bootstrap.Popover(popoverRef.current, {
            content: "Hello popover content!",
            title: "My Popover"
        })
      })
    
      return (
        <div className="p-4">
            <button className="btn btn-lg btn-danger" ref={popoverRef}>
                Click to toggle popover
            </button>
        </div>
      )
    }
    

    Codeply