DEV Community

Zain Butt
Zain Butt

Posted on

Preview images on upload with StimulusJS

In web development, providing users with a seamless experience for uploading images is crucial. One way to enhance this experience is by offering a preview of the uploaded image before submission. In this blog post, I'll walk you through how I integrated a new StimulusJS controller to achieve image upload previews.

Step 1: Creating and Registering the Controller File

First, let's create a new controller file for our image upload preview feature. In your StimulusJS controllers directory, create a new file, let's call it image_upload_preview_controller.js. Once the file is created, ensure that it's registered with your application by importing it in your index.js file.

application.register('uploads', Uploads)
Enter fullscreen mode Exit fullscreen mode

Step 2: Adding Required Code for Image Upload Preview

Inside the controller file, we'll need to add the necessary code. We'll define the required targets to manipulate: the form containing the file input and the container for the image preview.

export default class extends Controller{

  static targets = [ 'form', 'previewContainer' ]

  preview(event) {
    if(event.target.files.length > 0){
      let src = URL.createObjectURL(event.target.files[0]);
      this.previewContainerTarget.src = src;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Connecting HTML Form with the Controller

Finally, let's connect our HTML form with the controller. Add the data-controller attribute to the form element and specify the name of our controller (image-upload-preview) as the value. Also, include the data-target attribute with the targets we defined earlier.

<form data-controller="image-upload-preview" data-action="change->image-upload-preview#preview">
  <input type="file" name="image" accept="image/*" data-image-upload-preview-target="form">
  <img src="#" alt="Image Preview" data-image-upload-preview-target="previewContainer">
</form>
Enter fullscreen mode Exit fullscreen mode

✨ With just a few lines of code we were able to achieve this functionality. StimulusJS is very light weight and does not get in your way.

🤩 By organizing functionality into controllers, StimulusJS promotes clean and maintainable code, making it easier to manage and extend our applications.

👉🏻 I built this feature for my startup devtree where devs can build their portfolios sites and get in front of tech companies without any job search.

I share my journey with everyone on twitter and linkedin, follow to stay tuned.

Top comments (0)