12

I am trying to make a typescript + react fileinput component. However I'm getting typescript error 'Object is possibly null'. I have googled but couldn't find solution for this problem. How can I fix this problem without disabling typescript null check.

I'm getting errors on e.target.files[0]!

Here is the code below

import React from 'react';


    export default function ImageUpload() {
      const [selectedFile, setSelectedFile] = React.useState<File | string>('fileurl');
      const [imagePreviewUrl, setImagePreviewUrl] = React.useState<string | undefined | ArrayBuffer | null>();

      const fileChangedHandler = (e : React.ChangeEvent<HTMLInputElement>) => {
        setSelectedFile(e.target.files[0]!);

        const reader = new FileReader();

        reader.onloadend = () => {
          setImagePreviewUrl(reader.result);
        };

        reader.readAsDataURL(e.target.files[0]!);
      };

      const submit = () => {
        const fd = new FormData();

        fd.append('file', selectedFile);
      };

      let imagePreview = (<div className="previewText image-container">Please select an Image for Preview</div>);
      if (imagePreviewUrl) {
        imagePreview = (
          <div className="image-container">
            <img src={imagePreviewUrl} alt="icon" width="200" />
            {' '}
          </div>
        );
      }

      return (
        <div className="App">
          <input type="file" name="avatar" onChange={fileChangedHandler} />
          <button type="button" onClick={submit}> Upload </button>
          { imagePreview }
        </div>
      );
    }
kind user
  • 40,029
  • 7
  • 67
  • 77
Jonghyeon Lee
  • 147
  • 1
  • 1
  • 7

5 Answers5

30

HTMLInputElement has a built-in property files that is typeof FileList | null.

files: FileList | null; 

Simply secure the possibility that files is null.

if (!e.target.files) return;

At the beginning of the function.

kind user
  • 40,029
  • 7
  • 67
  • 77
8

Guys this is the proper way of handling this issue:

            e.target.files instanceof FileList
              ? reader.readAsDataURL(e.target.files[0]) : 'handle exception'

Hope this helps. Cheers!

5

From the code, I suspect that e.target is nullable. You could modify e.target.files[0]! to e.target!.files[0]!, which will make error go away because you will essentially tell the Typescript compiler that "it will not be null, trust me". But instead, I would advise to handle the null case properly - check for null or undefined and do something appropriate, depending on your app logic.

Max Yankov
  • 12,551
  • 12
  • 67
  • 135
1
if (!e.target.files || e.target.files.length === 0) {
      // you can display the error to the user
      console.error("Select a file");
      return;
    }
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
0

In my code it worked like this: I created a variable that received the HTML event, then created a variable that received all the event files and used the 'item' functionality at index 0, and then I was able to access the file

const handleSetFileName = (event: ChangeEvent<HTMLInputElement>) => {
  const files = event.target.files;
  setFileName(files?.item(0)?.name);
};
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
santosFk
  • 1
  • 1