Rails 7 bootstrap alert is not been dismissed

Viewed 557

I have followed this article https://www.bootrails.com/blog/rails-7-bootstrap-5-tutorial/ to display a bootstrap alert on my rails 7.0 app.

The alert is been displayed but not been dismissed when I click on the close button. Here is my code inside application.html.erb

<% flash.each do |key, value| %>
  <div class="alert alert-success alert-dismissible" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    <%= value %>
  </div>
<% end %>
3 Answers

Assuming you created your rails app with:

rails new APP_NAME --css=bootstrap ...

Which creates your app with ESBUILD and leaves you with a app/javascripts/application.js file looking like this:

// Entry point for the build script in your package.json
import "@hotwired/turbo-rails"
import "./controllers"
import * as bootstrap from "bootstrap"

You now need to code in the alert to use the imported bootstrap.

Add this below the bootstrap import line:

// Alerts
var alertList = document.querySelectorAll('.alert')
var alerts =  [].slice.call(alertList).map(function (element) {
  return new bootstrap.Alert(element)
});

This will turn on the event handlers

More can be found on the Bootstrap Docs page for each of the Components (the same applies to Modals and Popovers)

https://getbootstrap.com/docs/5.1/components/alerts/#initialize

This is the Bootstrap 5 version

<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
Related