I'm getting this TypeError
TypeError: Cannot read properties of undefined (reading 'files')
and cannot find a solution. my app is using react and I'm getting this error while handling a setState hook.
const handleCapImage = (event) => {
setPostImage(event.target.files[0]);
};
React element where I'm calling it
<input
type="file"
id="file"
ref={inputFile}
style={{ display: "none" }}
onChange={handleCapImage}
/>
CodePudding user response:
event.target
is refering to the element, from which the event originates. event.currentTarget
refers to the element that the eventListener is on. I guess your event is bubbeling to the element with the eventlistener, so you are accesing the wrong element (because I guess you want the element the eventListener is on)
CodePudding user response:
files is property of an input (HTMLInputElement) and not of the event.
So it should be event.currentTarget.files
Also make sure your input is actually of type="file"
Edit (Now that there is more info)
I cannot seem to find anything wrong with it. Make sure you are not doing something on that ref that triggers on change before the file is there. It's cheap, but as of now I would suggest just adding
if(event.target && event.target.files) {
setPostImage(event.target.files[0]);
} else {
setPostImage(undefined);
}
CodePudding user response:
inputFile.current.files[0]
should work if the handler function is inside your component.