import React, { useEffect, useRef } from "react"; const OffcanvasComponent = ({ id = "globalOffcanvas", title = "Offcanvas Title", placement = "start", // start | end | top | bottom children, show = false, onClose = () => { }, }) => { const offcanvasRef = useRef(null); const bsInstance = useRef(null); useEffect(() => { if (!offcanvasRef.current) return; // initialize once bsInstance.current = bootstrap.Offcanvas.getOrCreateInstance(offcanvasRef.current); const el = offcanvasRef.current; const handleHide = () => onClose(); el.addEventListener("hidden.bs.offcanvas", handleHide); return () => { el.removeEventListener("hidden.bs.offcanvas", handleHide); }; }, [onClose]); // react to `show` changes useEffect(() => { if (!bsInstance.current) return; if (show) bsInstance.current.show(); else bsInstance.current.hide(); }, [show]); return (
{title}
{children}
); }; export default OffcanvasComponent;