Hiển thị các loại file với reactJs
Published on April 09, 2025
reactjs
Để hỗ trợ hiển thị ảnh (jpg
, jpeg
, png
, gif
, webp
) và 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
| Xử lý | Hiển thị qua |
---|---|---|
| Hiển thị trực tiếp trong iframe | Trình duyệt |
| Gview (Google Docs Viewer) | Google Docs |
| Office viewer embed | Microsoft Office |
| Hiển thị | Ả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.