Creating interactive images that serve as input file selectors is a simple process

I am faced with the challenge of creating a clickable image that simulates an input file and captures the file name using Vue 3. However, I continuously encounter the error

Uncaught TypeError: Cannot read properties of null (reading 'click')
when attempting to click on the image.

Below is my code snippet:

 <template>
 <input class="form-control" type="file" @change="handleFileUpload($event, 'image1')"ref="fileInputRefs[0]" style="display: none;">
 <img src="front.png" class="images" @click="handleImageClick(0)">

 <input class="form-control" type="file" @change="handleFileUpload($event, 'image1')"ref="fileInputRefs[1]" style="display: none;">
 <img src="back.png" class="images" @click="handleImageClick(1)">


<script setup>
  const fileInputRefs = [
             ref(null),
             ref(null)
    ] 

 const handleImageClick = (index) => {
   fileInputRefs[index].value.click()
 }

const handleFileUpload = (event, id) => {
const fileList = event.target.files
const reader = new FileReader()
reader.readAsDataURL(fileList[0])
 reader.onload = () => {
  if (id === 'image1') {
     file1.value = {
      file: fileList[0],
     dataUrl: reader.result
   }
  } else if (id === 'image2') {
  file2.value = {
    file: fileList[0],
    dataUrl: reader.result
    }
  }
 }
}



</script>

Answer №1

Here is an example demonstrating how to bind a ref (:ref):

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const fileInputRefs = ref([])
    const handleImageClick = (index) => {
      fileInputRefs.value[index].click()
    }
    const handleFileUpload = (event, id) => {
      const fileList = event.target.files
      const reader = new FileReader()
      reader.readAsDataURL(fileList[0])
      reader.onload = () => {
        if (id === 'image1') {
          fileInputRefs.value = {
            file: fileList[0],
            dataUrl: reader.result
          }
        } else if (id === 'image2') {
          fileInputRefs.value[1] = {
            file: fileList[0],
            dataUrl: reader.result
          }
        }
      }
    }
    return {
      handleImageClick, handleFileUpload, fileInputRefs
    };
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <input class="form-control" type="file" @change="handleFileUpload($event, 'image1')" 
     :ref="el => { fileInputRefs[0] = el }" style="display: none;">
  <img src="front.png" class="images" @click="handleImageClick(0)">

  <input class="form-control" type="file" @change="handleFileUpload($event, 'image2')" 
    :ref="el => { fileInputRefs[1] = el }" style="display: none;">
  <img src="back.png" class="images" @click="handleImageClick(1)">
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to create a table using Jquery based on user input?

I'm trying to create a table for user inputs and classify them, but I'm having issues with the layout. When multiple inputs are added, they display in an awkward way. I've experimented with different methods, but the problem remains. Can som ...

Tips for eliminating any hidden image whitespace in a category filtering system

I recently implemented a category filter feature that hides images I don't need. When I click on the car logo at the top, I want to hide every element that doesn't have the "car" id. However, I'm facing an issue where hidden images still ret ...

Sorry, but React does not accept objects as valid children. Make sure the content you are passing is a valid React child element

I encountered an issue with rendering on a screen that involves receiving an object. The error message I received is as follows: Error: Objects are not valid as a React child (found: object with keys {_U, _V, _W, _X}). If you meant to render a collection o ...

Ways to handle the initial value of data from a successful ajax call in a unique manner compared to the subsequent

Below is the code to be considered: 'use strict'; $.getJSON('/img/content/galleries/', function(directories) { $("#gallery").text(""); for (var dirnum = 2; dirnum < directories.length - 1; dirnum++) { (function(dirnu ...

Show the React component upon clicking the Add button

I recently developed a React component that reveals a new section whenever the user clicks the "New Section" button. However, I have encountered an issue - I would like the component to display multiple sections based on how many times the button is clic ...

Utilizing React/Redux to handle asynchronous actions within reducers efficiently through chains or promises

In my React/Redux application, I am dealing with filtering and searching functionality that requires some manipulation of data between receiving the filters and updating the search query. To manage this, I have implemented a reference map of active filters ...

Vue email validation is failing to return a valid email address

I'm relatively new to Vue and have implemented email validation using the reg expression in my Vue script data for this project. By utilizing console.log(this.reg.test(this.email)) and observing the output while users input their email, the validation ...

What is the best way to list the choices associated with a specific category?

The Node.js package I'm currently working with requires an argument of a specific type, which I can see is defined through a TypeScript declaration as follows: export declare type ArgType = 'A' | 'B' | 'C'; I am interes ...

Continuous addition of Node structures in a tree

I am attempting to append a node tree to the DOM that has been created using createHTMLDocument. Originally, I approached it like this: (doc represents the node tree) while(doc.head.children.length > 0){ iframewin.document.head.appendChild(doc. ...

Simple Way to Show API Output in Plain Text (Beginner Inquiry)

I'm a beginner when it comes to using APIs. I'm trying to display the plain text response from this URL on my webpage: However, I'm encountering issues with getting it to work. Here's my code: <script src="https://ajax.googleap ...

Capturing the value of an input field within a controller in AngularJS

I have been programming with JSP and Angular JS. Currently, I am faced with a scenario where I need to work with a JSP page containing a hidden input field. To set the value of this input field, I am using a session attribute like so: String policy = (S ...

Having trouble with looping through subarrays using Javascript and JSON

I am attempting to iterate through a JSON object using Javascript (jQuery). Within the main JSON object, each object in the array contains embedded arrays of tags. My goal is to loop through all the files in the main object and simultaneously iterate thro ...

Leveraging the power of ReactJS alongside Google Tag Manager

Looking for a way to track my application using Google Tag Manager, I stumbled upon a popular package at https://www.npmjs.com/package/react-google-tag-manager. However, despite following the instructions, I am having trouble configuring it properly! Foll ...

Tips on disabling unnecessary server validation in ASP.NET

After implementing ValidatorEnable to disable a RequiredFieldValidator using JavaScript, I noticed that on postback the control being validated by the validator is still being validated. This suggests that even though I disabled the validator on the client ...

Unspecified value for element.style.width attribute on jsFiddle

Currently testing page templates for a forthcoming output from an HTTP server application. These pages are intended to be viewed on mobile browsers, so I'm focusing on creating a neat layout with scrolling capabilities to prevent any detrimental wrapp ...

Is there a way to display the output of a JavaScript function in an HTML document?

My current project involves coding a tool that allows users to calculate the area of a rectangle. The user is prompted to input the height and width, and then the website should display these values along with the calculated area in a table format. So far, ...

Tips on forcing Angular to refresh the screen during the middle of execution

In one of my Angular HTML pages, there seems to be a slight issue. Everything is working smoothly - the code, the directives (except for "ng-show" which never seems to work, but that's not the main concern here). However, when I have a button click e ...

Encountered ENOENT error - NodeJS

I'm currently working on creating an order of service by utilizing InDesign Server and passing variables through a form to the InDesign Script. However, I'm encountering the following error: /Users/rickybarnett/Desktop/curries-indesign/oos-w2p. ...

Combine and calculate the total of several columns using the Loadash library

In my Vue application, I am faced with the challenge of grouping an array by date and then calculating sums for multiple columns. The current method I have only allows me to group and sum one column: receiptsByDate: function(){ let byDate = _.groupBy(t ...

Learn the trick to make this floating icon descend gracefully and stick around!

I'm trying to create a scrolling effect for icons on my website where they stay fixed after scrolling down a certain number of pixels. I've managed to make the header fixed after scrolling, but I'm unsure how to achieve this specific effect. ...