javascriptruby-on-railsrubydropzone.js

How can I integrate Dropzone.js in Ruby on Rails 7.1.2


I'm attempting to integrate dropzone.js in Rail version 7.1.2, but JavaScript does not work. There appears to be a problem with importing node modules in the most recent version of Rails, so I manually added the CSS styles for the dropzone in the stylesheets' folder; however, this approach does not work for JavaScript. Another thing I observed is that the Dropzone js cdn works, but I need to load the JavaScript locally.

This is my application.js file

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


import jquery from "jquery"

//= require dropzone

window.jQuery = jquery
window.$ = jquery



window.Dropzone = require(dropzone)


// import "trix"
// import "@rails/actiontext/"


Solution

  • $ yarn add dropzone
    
    // app/javascript/application.js
    
    import Dropzone from "dropzone";
    
    document.addEventListener("turbo:load", function(event) {
      let myDropzone = new Dropzone(".dropzone");
      myDropzone.on("addedfile", file => {
        console.log(`File added: ${file.name}`);
      });
    })
    
    <!-- app/views/layouts/application.html.erb -->
    
    <link rel="stylesheet" href="https://unpkg.com/dropzone@5/dist/min/dropzone.min.css" type="text/css" />
    
    # _form.html.erb
    
    <%= form_with url: "/", class: :dropzone do |f| %>
      <%= f.file_field :img %>
    <% end %>