Để tạo một album ảnh trong react ta sử dụng package react-photo-album , cho phép hiển thị danh sách ảnh theo kiểu mansory - giống như trang Pinterest. Ngoài ra còn có thể xem từng ảnh theo kiểu slide show khi dùng kết hợp với package yet-another-react-lightbox
Đầu tiên, cài react-photo-album
npm i react-photo-album
Nhúng vào component ta muốn hiển thị danh sách ảnh
import PhotoAlbum from "react-photo-album";
const convertedImagesAlbum = [
{
src: "url_1_của_ảnh",
width: 500,
height: 200,
},
{
src: "url_2_của_ảnh",
width: 600,
height: 400,
},
...
]
<PhotoAlbum
layout="masonry"
photos={convertedImagesAlbum}
padding={8}
/>
Trong đó mỗi object 2 thuộc tính là width và height là chiều rộng và cao của ảnh được lưu lại khi upload ảnh lên, nếu không có 2 thuộc tính này layout sẽ không hiển thị như mong muốn.
Như vậy ta đã hiển thị được danh sách hình ảnh theo kiểu mansory. Bây giờ để khi click vào từng ảnh sẽ show modal xem chi tiết ảnh, sử dụng package yet-another-react-lightbox.
Cài đặt yet-another-react-lightbox.
nnpm i yet-another-react-lightbox
Nhúng vào component
import PhotoAlbum from "react-photo-album";
// Light box
import Lightbox from "yet-another-react-lightbox";
import "yet-another-react-lightbox/styles.css";
// import optional lightbox plugins
import Fullscreen from "yet-another-react-lightbox/plugins/fullscreen";
import Slideshow from "yet-another-react-lightbox/plugins/slideshow";
import Thumbnails from "yet-another-react-lightbox/plugins/thumbnails";
import Zoom from "yet-another-react-lightbox/plugins/zoom";
import "yet-another-react-lightbox/plugins/thumbnails.css";
export const AlbumAnh = () => {
const [index, setIndex] = useState(-1);
return(
<div>
<PhotoAlbum
layout="masonry"
photos={convertedImagesAlbum}
padding={8}
onClick={({ index }) => setIndex(index)}
/>
<Lightbox
slides={convertedImagesAlbum}
open={index >= 0}
index={index}
close={() => setIndex(-1)}
// enable optional lightbox plugins
plugins={[Fullscreen, Slideshow, Thumbnails, Zoom]}
/>
</div>
)
}
Lúc này khi click vào mỗi hình ảnh sẽ hiển thị modal cho phép ta xem ảnh rõ hơn và có thể xem theo kiểu slide show.
Tìm hiểu sâu hơn tại doc.