Since Bootstrap 5.0.0, it seems Bootstrap JS file must be loaded at the end of the <body> in order to render dynamically loaded Modals (and maybe other features). Check this issue on GitHub
Agree with this issue. This happens in bootstrap 5.x production release irrespective of how you initialize the modal. Either dynamically via JS or via Data attributes.
Currently the workaround to overcome this issue is to load the
bootstrap.bundle.jswithin the HTML body and not in the head. But it ideally cannot be the solution to this issue.
Do you know another workaround for this issue ?
// Error happens when I want to display a Modal using JS
var modal = new bootstrap.Modal(document.getElementById('my-modal');
modal.show();
// Uncaught TypeError: BACKDROP: Option "rootElement" provided type "null" but expected type "element".
// typeCheckConfig bootstrap.bundle.js:190
// typeCheckConfig bootstrap.bundle.js:184
// _getConfig bootstrap.bundle.js:4603
// Backdrop bootstrap.bundle.js:4539
// _initializeBackDrop bootstrap.bundle.js:4864
// Modal bootstrap.bundle.js:4721
// <anonymous> debugger eval code:2
Simplest workaround is to load our JS at the end of the <body> tag:
# app/views/layout/application.html.erb
<body>
<%= yield %>
<%# this `javascript_pack_tag` is initially inside the `<head>` tag
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
</body>