inzn
inzn

Reputation: 61

Asset Gallery to GatsbyImage (Gatsby v3+)

I have an asset gallery in my DatoCMS (only images) and would like to display them via GatsbyImage (from the new gatsby-plugin-image). However, as there are several images and not always the same amount of them in my blog posts, I need to write a loop (I guess?) but don’t know how to.

My post component:

export default function ProjectContent(props) {
    return (
        <div className="projectContent">
            <div className="projectContent__assets">
                <GatsbyImage image={props.imageGallery} />
            </div>
        </div>
    )
}

and the project template component:

export default function Project({ data }) {
    return (
        <>
            <ProjectContent 
                imageGallery={data.datoCmsProject.photos.gatsbyImageData}
            />
        </>
    )
}

    export const query = graphql`
    query($slug: String!)
      {
        datoCmsProject(slug: { eq: $slug }) {
          photos {
              gatsbyImageData(placeholder: BLURRED, layout: CONSTRAINED)
          }
        }
    }`

At the moment, no image is shown. I’ve managed to get GatsbyImage + DatoCMS to work already with single images, but not with the asset gallery.

Thanks for any and all help!

Upvotes: 1

Views: 184

Answers (1)

Ferran Buireu
Ferran Buireu

Reputation: 29320

I think are trying to do:

export default function Project({ data }) {

return (
    <>
        <ProjectContent 
            imageGallery={data.datoCmsProject.photos}
        />
    </>
 )
}

export const query = graphql`
query($slug: String!)
  {
    datoCmsProject(slug: { eq: $slug }) {
      photos {
          gatsbyImageData(placeholder: BLURRED, layout: CONSTRAINED)
      }
    }
}`

Note that you are sending the full array of photos (data.datoCmsProject.photos) to the child component.

And in the child component:

export default function ProjectContent(props) {
    return (
        <div className="projectContent">
            <div className="projectContent__assets">
                {props.imageGallery.map(photo=>{
                   return <GatsbyImage image={photo.gatsbyImageData} />
               })}
            </div>
        </div>
    )
}

It's quite self-explanatory but in your case, photos (sent as imageGallery to the child component) is an array of images. Once you get it there (props.imageGallery) you only need to loop through them, as you said, and print them using the new <GatsbyImage> component. Each instance of the photo (the iterable variable) has the gatsbyImageData required.

Upvotes: 1

Related Questions