Skip to content

PhotoSwipe Gallery

FiNAN uses PhotoSwipe v5 to provide a high-quality, touch-friendly image gallery experience. This is primarily used on representation pages (e.g., Sweden, Finland) to showcase community events.

The library is already installed in the project.

Terminal window
pnpm add photoswipe

To add a gallery to a page, follow these three steps: Markup, Script, and Styles.

PhotoSwipe requires a specific HTML structure. We use a container with a specific ID (e.g., gallery--sweden) and <a> tags linking to the full-size images.

<!-- Import your images -->
import eventImage1 from '../../assets/images/gallery/sweden/event-01.jpg';
<!-- Gallery Container -->
<div class="pswp-gallery grid grid-cols-1 sm:grid-cols-3 gap-4" id="gallery--sweden">
<!-- Individual Image Item -->
<a
href={eventImage1.src}
data-pswp-width={eventImage1.width}
data-pswp-height={eventImage1.height}
target="_blank"
class="block overflow-hidden rounded-lg shadow-md"
>
<img
src={eventImage1.src}
alt="Description of the event"
class="h-full w-full object-cover hover:scale-105 transition-transform"
/>
</a>
<!-- Add more images here -->
</div>

You need to initialize PhotoSwipe on the client. Add this <script> block at the bottom of your Astro page.

<script>
import PhotoSwipeLightbox from 'photoswipe/lightbox';
import 'photoswipe/style.css'; // Import styles here or in frontmatter
function initPhotoSwipe() {
const lightbox = new PhotoSwipeLightbox({
gallery: '#gallery--sweden', // Must match your container ID
children: 'a', // Selector for the image links
pswpModule: () => import('photoswipe'),
});
lightbox.init();
}
// Initialize on page load
initPhotoSwipe();
// Reinitialize on Astro page navigation (if using View Transitions)
document.addEventListener('astro:page-load', initPhotoSwipe);
</script>

Ensure you import the CSS. You can do this in the script (as shown above) or in the Astro frontmatter:

---
import 'photoswipe/style.css';
---

For the best performance and experience:

  • File Format: Use .jpg or .webp.
  • Dimensions: Full-size images should generally be around 2000-2500px wide.
  • Thumbnails: The <img> tag inside the link serves as the thumbnail. Astro’s image optimization will handle resizing if you use the <Image /> component, but standard <img> with imported assets works well for galleries too.
  1. Gallery doesn’t open?
    Check if the ID in new PhotoSwipeLightbox({ gallery: '#id' }) matches the div ID in your HTML.

  2. Zoom animation looks weird?
    Ensure data-pswp-width and data-pswp-height attributes match the actual pixel dimensions of the full-size image referenced in href.

  3. “Module not found”?
    Make sure you are using the dynamic import pswpModule: () => import('photoswipe') inside the config to keep the initial bundle size small.