How to check file extension using React

Issue

I want to check whether the file extension is an image or a pdf file. But using my code, only else part is working.

 const thumbs = files.map((selectedFile) => (
    <div key={selectedFile["name"]} className="d-flex">
      {selectedFile['.type'] == ".pdf" ? (
        <iframe src={selectedFile["preview"]} style={{ height: "20%", width: "20%" }} />
      ) : (
        <img
          src={selectedFile["preview"]}
          alt={selectedFile["name"]}
          style={{ height: "20%", width: "20%" }}
        />
      )}
    </div>
  ));

Solution

You would implement a function to check that. Example:

function getExtension(filename) {
  return filename.split('.').pop()
}

And then in the code:

getExtension(selectedFile["name"]).toLowerCase() === "pdf" ? ...

Answered By – Ryan Le

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.