Hiển thị các loại file với reactJs

Published on April 09, 2025

reactjs

View: 40

Để hỗ trợ hiển thị ảnh (jpg, jpeg, png, gif, webp)file Excel (xlsx, xls) trong component DocumentViewer, bạn chỉ cần mở rộng logic document.type trong phần return.


✅ Cập nhật đầy đủ DocumentViewer

return (
  <div>
    {document.type === "pdf" ? (
      <iframe
        ref={iframeRef}
        src={document.fileUrl}
        className="h-[800px] w-full border-0"
        title={document.title}
      />
    ) : document.type === "docx" ? (
      <iframe
        ref={iframeRef}
        src={`https://docs.google.com/gview?url=${encodeURIComponent(
          document.fileUrl
        )}&embedded=true`}
        className="h-[800px] w-full border-0"
        title={document.title}
      />
    ) : document.type === "pptx" ? (
      <iframe
        ref={iframeRef}
        src={`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(
          document.fileUrl
        )}`}
        className="w-full h-[800px] border-0"
        title={document.title}
      />
    ) : document.type === "xlsx" || document.type === "xls" ? (
      <iframe
        ref={iframeRef}
        src={`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(
          document.fileUrl
        )}`}
        className="w-full h-[800px] border-0"
        title={document.title}
      />
    ) : ["jpg", "jpeg", "png", "gif", "webp"].includes(document.type) ? (
      <div className="flex justify-center">
        <img
          src={document.fileUrl}
          alt={document.title}
          className="max-h-[800px] max-w-full object-contain"
        />
      </div>
    ) : (
      <div className="flex items-center justify-center">
        <p className="text-muted-foreground">
          Không hỗ trợ xem trước cho loại tài liệu này.
        </p>
      </div>
    )}
  </div>
);

📌 Cách hoạt động

type

Xử lý

Hiển thị qua

pdf

Hiển thị trực tiếp trong iframe

Trình duyệt

docx

Gview (Google Docs Viewer)

Google Docs

pptx, xlsx

Office viewer embed

Microsoft Office

jpg, png...

Hiển thị <img>

Ảnh trực tiếp


⚠️ Lưu ý về document.type

Đảm bảo backend hoặc nơi truyền dữ liệu gửi đúng type tương ứng như: "pdf", "docx", "pptx", "xlsx", "png"...

Nếu bạn cần mình viết đoạn code tự động detect type từ fileUrl thì cũng được nhé.

Related Articles

How to Improve Your Blog Design

Learn tips and tricks to enhance your blog's appearance and usability.

Top Blogging Tools in 2024

Discover the best tools to elevate your blogging experience.

Writing Content that Converts

Learn the art of creating engaging and effective blog content.

Ôn tập là dễ

Ôn tập là dễ

Nền tảng thi trắc nghiệm số 1 Việt Nam giúp bạn tạo, quản lý và chia sẻ bộ đề một cách nhanh chóng và dễ dàng.

© 2025 Ôn tập là dễ. Tất cả các quyền được bảo lưu.