ReactJS+GatsbyJS中react-photo-gallery适配Contentful GraphQL数据问题
Hey Darren, I’ve run into this exact mismatch before—react-photo-gallery expects a specific structure for its photos prop, and the raw data from Contentful’s Gatsby source doesn’t line up out of the box. Let’s fix this step by step.
First, let’s recall what react-photo-gallery needs: each photo object in the array must have src (the image URL), width, and height as core properties. Optional but useful additions are srcSet (for responsive loading) and alt (for accessibility).
Step 1: Update Your GraphQL Query
First, make sure you’re pulling in all the data you need—including the image alt text (super important for accessibility!) alongside the sizes data. Modify your query like this:
query galleryQuery($slug: String!) { contentfulImageGallery(slug: {eq: $slug}) { summerGallery { alt # Add this to get the image's alt text from Contentful sizes(maxWidth: 1500) { ...GatsbyContentfulSizes_withWebp_noBase64 } } } }
Step 2: Transform the Data to Match the Component’s Format
The sizes object from Contentful has all the values we need, but they’re nested. We’ll map over the raw gallery data to reshape it into the structure react-photo-gallery expects.
Here’s how to implement this in your component:
import React from 'react'; import Gallery from 'react-photo-gallery'; import get from 'lodash/get'; const YourGalleryComponent = (props) => { // Fetch the raw gallery data from props const rawGalleryItems = get(props, 'data.contentfulImageGallery.summerGallery', []); // Transform each item to fit react-photo-gallery's requirements const galleryPhotos = rawGalleryItems.map((item) => { const { sizes, alt } = item; return { src: sizes.src, // The main image URL srcSet: sizes.srcSet, // Optional: enables responsive image loading width: sizes.width, // Must be a number (which it is from Contentful) height: sizes.height, // Also a number alt: alt || 'Gallery image', // Fallback alt text if none is set in Contentful }; }); return ( <div className="gallery-container"> <Gallery photos={galleryPhotos} /> </div> ); }; export default YourGalleryComponent;
Quick Troubleshooting Tips
- Double-check data types: Ensure
widthandheightare numbers (they should be, since Gatsby’s Contentful source returns them as numbers). If you see strings for some reason, parse them withparseInt(). - Verify the
srcvalue: Thesizes.srcfield is the full URL of the image at your specifiedmaxWidth(1500px here). If you need a different size, adjust themaxWidthparameter in your GraphQL query. - Check react-photo-gallery version: If you’re using an older version, confirm the prop names haven’t changed (though
photosand the core image properties have stayed consistent for most recent versions).
That should get your gallery rendering correctly! Let me know if you hit any snags along the way.
内容的提问来源于stack exchange,提问作者Darren

