Image Gallery for React
- Install PhotoSwipe, for example
npm i photoswipe#beta --s
- Generate HTML markup for your gallery
- Initialize PhotoSwipe when component with HTML markup is mounted.
- Don't forget to call destroy() when component is unmounted to avoid memory leak.
Here's how to create a simple image grid component:
import React from "react";
import PhotoSwipeLightbox from "photoswipe/dist/photoswipe-lightbox.esm.js";
import "photoswipe/dist/photoswipe.css";
class SimpleGallery extends React.Component {
componentDidMount() {
if (!this.lightbox) {
this.lightbox = new PhotoSwipeLightbox({
gallery: "#" + this.props.galleryID,
children: "a",
pswpModule: () => import("photoswipe")
});
this.lightbox.init();
}
}
componentWillUnmount() {
if (this.lightbox) {
this.lightbox.destroy();
this.lightbox = null;
}
}
render() {
return (
<div className="pswp-gallery" id={this.props.galleryID}>
{this.props.images.map((image, index) => (
<a
href={image.largeURL}
data-pswp-width={image.width}
data-pswp-height={image.height}
key={this.props.galleryID + "-" + index}
target="_blank"
rel="noreferrer"
>
<img src={image.thumbnailURL} alt="" />
</a>
))}
</div>
);
}
}
export default SimpleGallery;
Please refer to codesandbox below for the full code.