0

I'm trying to add a Dropzone to a page dynamically but I either get an "Uncaught Error: Invalid dropzone element. at new $3ed2...." or "Uncaught ReferenceError: Dropzone is not defined" while trying to use the examples from Dropzone.js.

Basically I have a function like:

export function UploadComponent(props) {
....
return html`<div>
<form action="/target" class="dropzone" id="my-dropzone">Upload files here</form>
</div>
}

The function gets called after the page is loaded by a button click so that dropzone is added to the screen. My issue is getting the Dropzone.js scripts added after the HTML is rendered. Any advice on this is much appreciated! Wondering if the only way to do this is to have something polling to check for the html component to be loaded.

Different variations of the Dropzone.js documentation

1
  • Can you provide the whole file instead, you might just need to import the library Commented May 8 at 22:25

1 Answer 1

0

To dynamically integrate Dropzone.js into your application, especially when elements are added to the DOM after the initial page load (like in your case with a button click), you need to ensure that the Dropzone library is loaded and available before you try to attach it to a form element. Here are some steps and tips to help you set up Dropzone.js correctly in such scenarios:

Ensure Dropzone.js is Loaded

First, make sure that the Dropzone script is included in your page. You can include it in the section of your HTML to ensure it's loaded before your scripts run. If you prefer to load it dynamically, you can do so by creating a script element and appending it to the DOM.

<!-- Static loading in HTML -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/dropzone.min.js"></script>

Then Initialize Dropzone After Element is in the DOM

Since your form is added dynamically, you must initialize Dropzone after the form is actually in the DOM. You can do this directly in the function that handles the button click, after the HTML for the form is appended.

export function UploadComponent(props) {
    // Assuming this function is called after the button click and the form is added to the DOM
    const formElement = document.querySelector('#my-dropzone');
    if (formElement) {
        // Check if Dropzone is defined or wait for it if loaded asynchronously
        if (typeof Dropzone !== 'undefined') {
            new Dropzone(formElement, { url: '/target' });
        } else {
            console.error('Dropzone.js is not loaded');
        }
    } else {
        console.error('Form element not found');
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.