Search code examples
javascriptreactjstypescriptcomponents

typescript Object is possibly null when getting files from event


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>
      );
    }

Solution

  • 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.