I am currently following a tutorial on building a drag and drop file uploader using StencilJS for some practice and fun. However, I have encountered an error in the code.
Below is a snippet of the code, but I can provide more if necessary.
@Component({
tag: 'dynamic-uploader',
styleUrl: 'dynamic-uploader.css',
shadow: true,
})
export class DynamicUploader {
@Element() public dynamicUploader: HTMLElement;
@State() dropzoneActive: boolean = false;
@State() stagedFiles: Array<StagedFile> = [];
componentDidLoad() {
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
this.dynamicUploader.addEventListener(eventName, this.handleDefaultPrevention, false);
document.body.addEventListener(eventName, this.handleDefaultPrevention, false);
});
['dragenter', 'dragover'].forEach(eventName => {
this.dynamicUploader.addEventListener(eventName, () => (this.dropzoneActive = true), false);
});
['dragleave', 'drop'].forEach(eventName => {
this.dynamicUploader.addEventListener(eventName, () => (this.dropzoneActive = false), false);
});
this.dynamicUploader.addEventListener('drop', this.handleDroppedFile, false);
}
handleDefaultPrevention(event: Event) {
event.preventDefault();
event.stopPropagation();
}
handleFiles(file) {
// files = [...files];
// files.forEach(this.handleFilePreview);
}
// handleFiles = files => {
// files = [...files];
// files.forEach(this.handleFilePreview);
// };
handleDroppedFile(event: InputEvent) {
let dataTransfer = event.dataTransfer;
let files = dataTransfer.files;
console.log(this.dynamicUploader);
Array.from(files).forEach(i => this.handleFilePreview(i));
}
handleFilePreview(file: File) {
this.stagedFiles = [...this.stagedFiles, <staged-file file={file}></staged-file>];
}
render() {
return (
<Host>
{`The dropzone is ${this.dropzoneActive ? 'active' : 'inactive'`}
<form id="dynamic-uploader" class={{ 'is-active': this.dropzoneActive }}>
<p>Upload Evidence</p>
<input type="file" id="file-input" multiple accept="image/*" />
<label class="button" htmlFor="file-input">
Select some files
</label>
</form>
<div class="stage-files">{this.stagedFiles}</div>
</Host>
);
}
}
It seems that the handleFiles method is not working as expected during debugging. If written as an arrow function, it doesn't seem to exist, which led me to believe there were scope issues. However, rewriting it in the conventional way does not resolve the issue either.