Home > OS >  Sweet Alert 2 is not working properly in Rails 7 Application
Sweet Alert 2 is not working properly in Rails 7 Application

Time:01-31

I attempted to integrate the Sweet Alert 2 java-script library for customising standard alert boxes into a Rails 7 application, but I received the following error message: "Swal is not defined." I'm using Ruby 3 and Rails 7.

I initially attempted to use the "sweet-alert2-rails" gem in my Rails application, but there are no current updates available. I therefore attempted to accomplish this using import map, and I did so by running the following line.

bin/importmap pin sweetalert2

On top of that, I added the lines below to the application.js

import Swal from "sweetalert2"

I encountered the aforementioned problem when attempting to use "Sweet Alert 2" in my view files.

Swal.fire(
  'Good job!',
  'You clicked the button!',
  'success'
)

To integrate Sweet Alerts into my Rails application, I used these links.

https://sweetalert2.github.io/

https://github.com/sweetalert2/sweetalert2

CodePudding user response:

You defined Swal in application.js using import Swal from "sweetalert2", and then you are trying to use it in your view files, so it is saying that Swal is not defined.

Previously, in rails 6, we added "sweet alert" using "yarn install," and the same error occurred. Hence, to solve this error either in Rails 6 or in Rails 7, you need to add the following line inside your application.js.

import Swal from 'sweetalert2';
window.Swal = Swal;

Adding window.Swal will undoubtedly fix your problem in Rails 7.


You can find references on my blog and in my GitHub repository. I have written this article for Rails 7.0.4 and Ruby 3.1.0. and also implemented the code for the same version.

Blog : https://rutikkpatel.medium.com/sweet-alert-2-in-ruby-on-rails-7-3f4cffe1ea5f

GitHub Repository : https://github.com/rutikkpatel/Sweet-Alert-Rails

I hope that will help you with your issue.

  • Related