Gatsby: What's the best way to add dynamic images in page components?

Created on 1 Jan 2018  路  5Comments  路  Source: gatsbyjs/gatsby

I've been building a site that primarily uses Page components and was wondering about guidance on best practices for images when you have:

  • Pages based on page components
  • Want to have optimized images on the page that I can resize/format in code

I'd be happy to add these to documentation if they seem right. And if not I'd love to learn the best way to do this.
Basically I've been using

  • gatsby-image
  • gatsby-transformer-sharp
  • gatsby-plugin-sharp
  • gatsby-source-filesystem

I then query the file I want to use as my image and format it (with resolutions for fixed size, size with images that should stretch)

export const query = graphql`
  query indexQuery {
    fileName:file(relativePath: { eq: "images/myimage.jpg" }) {
      childImageSharp {
        resolutions(width: 400) {
          ...GatsbyImageSharpResolutions
        }
      }
    }
  }
`;

I then can use the "fragment" ( like "...GatsbyImageSharpResolutions") in gatsby-image

import Img from 'gatsby-image'
const imagePage = ({ data }) => {
  <Img resolutions={data.fileName.childImageSharp.resolutions} />
}
question or discussion

Most helpful comment

@nimaiwalsh I have a PR in for some docs on that https://github.com/gatsbyjs/gatsby/pull/4191 on my own site I've been using "image fragments" which are like standard queries that format the images for my gallery on my portfolio. Here's my fragments
https://github.com/melissamcewen/melissamcewen/blob/master/src/utils/imagefragments.js
and here is an example:
https://github.com/melissamcewen/melissamcewen/blob/master/src/pages/portfolio/index.js

All 5 comments

Yup this is the recommended approach! There's the gatsby-image readme as well as https://using-gatsby-image.gatsbyjs.org

Would love suggestions / PRs for more/better documentation. Were you thinking about a tutorial perhaps for using them?

nice @melissamcewen ! I'm trying to do something similar and hitting roadblocks. Would love if you unpacked this and opened a docs PR. I find the gatsby-image docs lacking and your learnings/insights would be super helpful. 馃 馃憤

What is the best method to query and map multiple images say for a Gallery/Grid of images?

Great project by the way! Great work.

@nimaiwalsh I have a PR in for some docs on that https://github.com/gatsbyjs/gatsby/pull/4191 on my own site I've been using "image fragments" which are like standard queries that format the images for my gallery on my portfolio. Here's my fragments
https://github.com/melissamcewen/melissamcewen/blob/master/src/utils/imagefragments.js
and here is an example:
https://github.com/melissamcewen/melissamcewen/blob/master/src/pages/portfolio/index.js

Closing as this has been added to the docs in #4191 馃帀

Was this page helpful?
0 / 5 - 0 ratings