The absence of property 'files' on type 'EventTarget' in Vue 3 Typescript Composition API

With Vue 3's Composition API, I am aiming to dynamically display the selected photo as the background image of a button temporarily. Upon uploading, the button's background image should revert back to its default state.

Initially, I encountered errors such as 'Object is possibly null' with photo.value and e.target. I managed to resolve these issues using conditional statements. Please advise if this approach aligns with Vue 3 best practices.

Currently, I am facing an error stating

'Property 'files' does not exist on type 'EventTarget''
in relation to e.target.files[0]. Could this be a type declaration problem? What would be the optimal way to address this issue?

The proposed online solution

(<HTMLInputElement>e.target).files[0]
appears ineffective in a Vue context, resulting in the message 'Object is possibly null'.

<template>
    <button ref="photo" @click="uploadPhoto"></button>
    <input type="file" ref="photoInput" @change="showTempPhoto" style="display: none" />
</template>
setup(){
    const photo = ref<HTMLDivElement | null>(null)
    const photoInput = ref<HTMLInputElement | null>(null)

    const uploadPhoto = () => {
        photoInput.value?.click()
    }

    const showTempPhoto = (e: Event) => {
        if (photo.value && e.target){
            const url = URL.createObjectURL(e.target.files[0])
            photo.value.style.backgroundImage = url
            photo.value.onload = () => URL.revokeObjectURL(url)
        }
    }
}

Answer №1

Within the Event class, it is possible that there may or may not be a target present, as demonstrated here:

let my_event = new Event('event_type');
console.log(my_event.target)

// returns null

In typescript, it is also uncertain of the target's element type and whether it is null or not; hence, you must explicitly verify if target is not null and then cast e.target to HTMLInputElement:

const showTempPhoto = (e: Event) => {
    if (photo.value && e.target !== null){
        const url = URL.createObjectURL((<HTMLInputElement>e.target).files[0])
        photo.value.style.backgroundImage = url
        photo.value.onload = () => URL.revokeObjectURL(url)
    }
}

Answer №2

Breaking down the URL declaration was key in resolving the issue at hand.

const element = <HTMLSelectElement>e.element

After performing a null check,

const imageUrl = URL.createObjectURL(element.files && element.files[0])

and then finishing up with cleaning up the assignment of backgroundImage

imageContainer.style.backgroundImage = `url('${imageUrl}')`

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

Vue 3: `defineProps` allows components to locally reference declared variables

Why am I receiving a warning error message: defineProps is referencing locally declared variables. eslint(vue/valid-define-props) whenever I utilize a custom validator in props within an SFC <script setup> mode: <script setup> import { valid ...

What is the best way to determine if a checkbox has been selected in ExtJS?

I have a panel with a checkbox inside it. I am trying to figure out how to check if the checkbox is selected or not using an external function. Can someone please assist me with this? this.currentManagerPanel = new Ext.Panel({ border: false, wid ...

The cross-domain AJAX request fails to receive a response

I am currently working on validating PAN card details. I am utilizing an AJAX call to verify the PAN card entered by the user, sending the PAN number to this URL: . The data is being sent to the following URL using AJAX call: function callbackFnc(data) { ...

Can you recommend a suitable function for matching pairs in TypeScript or FlowType?

My TypeScript knowledge led me to create this implementation of a pairs function: const pairs = <A, B extends keyof A>(a: A): [keyof A, A[B]][] => { const mapper = (k: keyof A): [keyof A, A[B]] => [k, a[k]] return Object.keys(a).map(mapper ...

Challenges with React Native's AsyncStorage

When I try to access data stored in asyncStorage using the 'getToken' and 'getMail' functions in the code snippet below, I encounter an issue where the data appears empty when I initially open the page on the emulator. However, upon sav ...

When attempting to pass props to children, Typescript triggers an error message

I am facing an issue with a component that renders a child based on the specific "league" a user is viewing, such as MLB. Typescript is throwing an error because I am not passing the correct props to the child component. However, the parent component has t ...

Angular AutoComplete feature does not accurately filter the list items

I need to implement an auto-complete feature for the county field due to a large number of items in the list causing inconvenience to users who have to scroll extensively. Currently, there are two issues with the code. The first problem is that although t ...

Disabling Immediate Row Checkbox in Angular Datatable Based on Column Data

Is there a way to prevent the checkbox in a row from being checked based on certain column data? In my datatable, I need to implement a condition where if firstname="Superman", then the checkbox for that particular row should be disabled to preve ...

What could be the reason for the malfunctioning of the Angular options tracking by ID feature?

I seem to be facing an issue with my code: There is an object that holds the id of an item, along with an array containing these items. I require a 'select' element to display the currently selected item and allow for changing the selection. Th ...

Create a horizontal scrolling div with a fixed position

Even though this topic has been discussed numerous times, I have not found any solutions that work for me. My webpage has a sidebar on the left with position:fixed in CSS, and I want it to scroll horizontally along with the rest of the content. For the he ...

Guidelines for placing an HTML element in relation to another HTML element using CSS or JavaScript

Is there a way to position an HTML element in relation to another using CSS or JavaScript? I have attempted to copy the inner HTML of the "second-element" and append it inside the "first-element", but this approach is causing issues with other functional ...

Filtering data from Arduino using web serial communication

My setup consists of an Arduino kit connected to a webserial API that sends data to an HTML div identified by the id 'target'. Currently, all the data is being logged into one stream despite having multiple dials and switches on the Arduino. Th ...

What is the best way to ensure an AJAX get-request waits for the page to finish rendering before providing a response?

I've been working on a Greasemonkey Script for a specific section of this website (Site1). Site1 offers various deals and discounts, and my script is designed to perform the following task: When a user visits an offer on Site1, the script checks with ...

Resetting forms in AngularJS 1.5.6 with ng-messages functionality

I have been searching for solutions on Stackoverflow regarding how to reset a form, but I am still not able to figure it out. Even though the input was valid, the error message kept showing up. Upon debugging the application, I noticed that the message was ...

What is the best way to access attributes from a div element?

I am currently working on extracting attributes from within a div tag, specifically the custom attributes of the first child element. I am using web scraping techniques with Node.js and Puppeteer. My goal is to retrieve the custom attributes data-ticker, d ...

Transforming a string into a JavaScript array using regular expressions

Excuse me if this question has already been asked (this is my first time asking). The content of my string looks like this (after removing the whitespace): "#home #blog description of page here ##article1 ##article2 #contact" When parsed, it will produce ...

How to retrieve multiple values from a single select dropdown form field using React

In my React Material form, I have a select dropdown that displays options from an array of objects. Each option shows the name field, which is set as the value attribute (cpuParent.name). However, I also need to access the wattage field (cpuParent.wattage) ...

Header Express does not contain any cookies, which may vary based on the specific path

In my express.js app, I have two controllers set up for handling requests: /auth and /posts. I've implemented token authorization to set the Authorization cookie, but I'm encountering an issue when making a request to /posts. The request goes th ...

Formatting ternary expressions in VueJS

VueJS is being utilized by me and it contains an expression as shown below: {{ item.recommendation ? "PS4" : "Xbox" }} Is there a way to make "PS4" appear in red color and "Xbox" in blue color within the expression by incorporating CSS ...

Guide on making a Vue.js show/hide button for each element on a webpage

There is a feature to toggle between displaying "more" or "less" text, but currently the @click event affects all elements causing them to show all the text at once. I realize that I need to pass a unique value to distinguish each element, but I am curren ...