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

Nguyễn Quang Minh

3 min read
230 views

Để 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é.

Nguyễn Quang Minh

Passionate developer and writer sharing insights about technology, programming, and digital innovation. Follow for more content about web development and tech trends.

1.2K followers
Ô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.

    🔥 Mua sắm ngay trên Shopee!
    Giúp mình duy trì trang web! 🎉