djmetzle.io

Gatsby Gallery

01 February, 2020

I wanted a photo gallery for my Gatsby site.

I gave gatsby-theme-gallery a try, and it looks good. Its sharp, and dark, and themeable, and responsive. I added a handful of photos, and it looked great.

Except!

The ordering is backwards! Old photos are at the top, new ones are at the bottom. That is a show stopper. Checking out the source the sort order is hard-coded, and not customizable.

Seems like we need to build our own gallery!

Bundled with Gatsby is the gatsby-transformer-sharp plugin. This transformer will automatically apply to nodes found by source plugins. I chose to add another source-filesystem resolution to my gatsby-config.js:

  ...
},
{
  resolve: `gatsby-source-filesystem`,
  options: {
    name: `photos`,
    path: `${__dirname}/photos`,
  },
},
{
  ...

This lets us add a query that can select just the set of files from that folder. The query looks something like:

allFile(filter: {sourceInstanceName: {eq: "photos"}}) {
  edges {
    node {
      id
    }
  }
}

We only find the files from the photos source plugin instance.

We can extract off of these files specifically image data generated by the sharp transform:

allFile(filter: {sourceInstanceName: {eq: "photos"}}) {
  edges {
    node {
      childImageSharp {
        id
        sizes(maxWidth: 1240 ) {
          ...GatsbyImageSharpSizes
        }
      }
    }
  }
}

Next, we can use the gatsby-image package. This gives us a nice responsive component that we can use to display our images. The gatsby-image component will accept the output of our Sharp query, directly, and render our image.

import Img from "gatsby-image"

const GalleryImage = ({image}) => {
  return (
    <>
      <Img sizes={image.sizes} />
    </>
  )
}

const Gallery = ({data}) => {
  const files = data.allFile.edges;
  return files.map((file) => {
    const image = file.node.childImageSharp
    return(
      <GalleryImage
        key={image.id}
        image={image}
      />
    )
  })
}

Gatsby Image is very powerful! Give the docs and read to see the different ways we can use it.

From here, we just need to twiddle CSS until the site looks the way we want.

Checkout my Photos site to see this in action!