react-photoswipe-gallery is a React component wrapper that integrates the PhotoSwipe JavaScript image gallery library into React applications. It simplifies the process of creating responsive image galleries by abstracting PhotoSwipe's imperative API into declarative React components like `Gallery` and `Item`. The current stable version is 4.0.0, which includes breaking changes focused on security and refactoring. The project maintains a moderate release cadence, with patch and minor updates appearing every few months, and major versions released less frequently. Its key differentiator lies in providing a native React experience for PhotoSwipe, managing the gallery's lifecycle and element references within the React component model, reducing boilerplate code, and ensuring compatibility with modern React features.
npm install react-photoswipe-galleryVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to set up a basic image gallery using the `Gallery` and `Item` components. It includes the necessary PhotoSwipe CSS, custom options for the gallery, and correctly handles image references and click events to open the lightbox, showcasing two sample images.
Refactor captions to use plain text only. If rich text is essential, consider rendering it externally or sanitizing any HTML content rigorously before passing it, although direct HTML is no longer officially supported for security reasons.
Update `Item` components to use the ref callback pattern correctly. Ensure the `ref` provided by the render prop is always assigned to the target HTML element, e.g., `ref={ref as React.MutableRefObject<HTMLElement>}` in TypeScript, and remove any explicit `ref` casting if previously used.Ensure that your installed `photoswipe` package version adheres to the peer dependency requirements specified by `react-photoswipe-gallery`. Upgrade or downgrade `photoswipe` as necessary to match the expected range.
It is strongly recommended to upgrade to `react-photoswipe-gallery` v4.0.0 or later to benefit from the built-in XSS protection. If upgrading is not immediately possible, meticulously sanitize all content provided to the `caption` prop to prevent arbitrary script execution.
Ensure the `ref` prop passed down from the `Item` component's render function is correctly assigned to your `<img>` or `<a>` element, like `ref={ref as React.MutableRefObject<HTMLImageElement>}` (for TypeScript) or `ref={(el) => { if (ref) ref.current = el; }}` for a callback pattern.Verify that `Item` components are always direct children of a `Gallery` component. Ensure `Item` is imported as a named export: `import { Item } from 'react-photoswipe-gallery'`.First, install `photoswipe` (`npm install photoswipe`) and ensure its version is compatible. Then, add `import 'photoswipe/dist/photoswipe.css';` to your application's entry point or relevant component file to include the necessary styles.