32
votes

I’m thinking of using Gatsby-Image for my next project and has been playing around with it a little.

I got it to work on my test project but then I came up with a use case that I would like to use the from Gatsby much like a regular <img src”image.png”> tag. My question is therefore how I can make the Gatsby component reusable?

import React from "react"
import { StaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"
function renderImage({ file }) {
  console.log({ file })
  return <Img fluid={file.childImageSharp.fluid} />
}

// Stateless Image component which i guess will recieve src value as a prop?
// Returns a StaticQuery component with query prop and render prop. Query prop has the graphql query to recieve the images and render prop returns a renderImage function which in return, returns a Img component från Gatsby with set attributes.
const Image = () => (
  <StaticQuery
    query={graphql`
      query {
        file(relativePath: { eq: "gatsby-astronaut.png" }) {
          childImageSharp {
            fluid(maxWidth: 300) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    `}
    // render={data => <Img fluid={data.placeholderImage.childImageSharp.fluid} />}
    render={renderImage}
  />
)
export default Image

My optimal use case would be to make a dynamic request to my relativePath which is defined in my Gatsby.config file and then combine the src prop in each Gatsby and match it with all my images in my assets file and then display it. Do anyone of you know if this is even possible with ?

I read in the docs that Static Query can't take variables - only pages. But I don't want my images to be associated with a page - I want to use this component anywhere I want - like a regular img tag.

Hope I’ve made myself clear. Please ask if you have any questions.

This is an example: https://codesandbox.io/s/py5n24wk27

Thanks beforehand, Erik

4
Since gatsby-image requires pre-processing from gatsby itself, it's not possible to make it truly dynamic at runtime as with an img tag. You have to use StaticQuery or get the data in the regular page query. - Tholle
I've deleted my answer because I just tried it and can confirm that it's not possible currently. There's a technical limitation, Gatsby actually extracts and parses the queries ahead of time and it doesn't evaluate dynamic code as it's doing that. Seems like a pretty concrete technical consideration. Source: github.com/gatsbyjs/rfcs/pull/3 - Richard Vanbergen
Hmm, ok I understand. The search continues I guess! Thanks - erikos93

4 Answers

44
votes

I've been searching for this answer as well. Hopefully this answers your question:

The final code:

import React from 'react';
import { StaticQuery, graphql } from 'gatsby';
import Img from 'gatsby-image';

// Note: You can change "images" to whatever you'd like.

const Image = props => (
  <StaticQuery
    query={graphql`
      query {
        images: allFile {
          edges {
            node {
              relativePath
              name
              childImageSharp {
                fluid(maxWidth: 600) {
                  ...GatsbyImageSharpFluid
                }
              }
            }
          }
        }
      }
    `}
    render={data => {
      const image = data.images.edges.find(n => {
        return n.node.relativePath.includes(props.filename);
      });
      if (!image) {
        return null;
      }

      //const imageSizes = image.node.childImageSharp.sizes; sizes={imageSizes}
      return <Img alt={props.alt} fluid={image.node.childImageSharp.fluid} />;
    }}
  />
);

export default Image;

Using the image:

import Image from '../components/Image';
<div style={{ maxWidth: `300px` }}>
    <Image alt="Gatsby in Space" filename="gatsby-astronaut.png" />
</div>

Explanation

Because StaticQuery doesn't support string interpolation in its template literal, we can't really pass it any props. Instead we will try and handle check for props in the StaticQuery's Render portion.

Caveats

I'm not 100% sure if this affects compiling time since we are scanning all images. If it does, please let me know!

Update: If you have many images, bundle size can get quite large as this solution does scan ALL images.

Further customization

You can adjust the code to show a placeholder image if no props are passed.

Alternatives

That said, there is another way you could tackle this but with a bit more work/code.

Sources

  • I modified the code from this article. (Please note that the article was using deprecated code.)
10
votes

Unfortunately from what I can gather the best solution is to write out individual js files for images.

In @RodrigoLeon's approach, it will cause bundle size to increase DRAMATICALLY. Especially if say you have more than 50 images. Because anytime you use this and loop through all images you create references to them in the component file. So I would not recommend doing it this way.

4
votes

The site I am building is an e-commerce platform with thousands of images (for all the products). This presented a major issue with using gatsby which is querying images. For a long time, I had a component that queried all images and matched them up to their respective product. (Like proposed in this ) This is highly inefficient, throwing warnings about the duration of the query.

An alternate to this is the attach the imageFile to the product on the data level, rather than when trying to render.

src/gatsby-api/create-resolvers/index.js

const resolvers = {
    AWSAppSync_Product: {
        imageFile: {
            type: 'File',
            resolve: async (source, args, context, info) => {
                const node = await context.nodeModel.runQuery({
                    query: {
                        filter: {
                            Key: { eq: source.image1 }
                        }
                    },
                    type: 'S3Object',
                    firstOnly: true
                });

                if (node && node.imageFile) return node.imageFile;
            }
        },
    },
}

module.exports = {
    resolvers
}

gatsby-node.js

exports.createResolvers = async ({ createResolvers }) => {
    createResolvers(resolvers)
}

src/components/image/index.js

import React from 'react'
import Img from 'gatsby-image'

export const Image = props => {
  if (props.imageFile && props.imageFile.childImageSharp && props.imageFile.childImageSharp.fluid) {
    return <Img className={props.imgClassName} alt={props.alt} fluid={props.imageFile.childImageSharp.fluid} />;
  }
};

Then use it like:

<Image
  imageFile={product.imageFile}
  alt=""
/>

AWSAppSync_Product is the type of node I am attaching my File to. (which can be found in the graphql playground on localhost). The resolve will match the Key of the S3Object with image1 (which is a string) on the product. This allows me to directly use the product images without having to run a query inside the image component.

In my opinion, this is a valuable piece of information once you wrap your head around it and it certainly has helped me a lot.

0
votes

If you use Wordpress with WP GraphQL and want to load some posts, dynamically, you will face the same issue. You will be unable to use the great pre-processing features like lower the quality and use rough base64 placeholders. As many before mentioned @RodrigoLeon solution will work, but you will face a huge load if your site grows in images, eventually.

Since my website will feature a lot of posts and will feature dynamic loading such posts, I had to come up with a solution that is, at least, acceptable. What I end up doing is generating the childImageSharp (and providing a generic base64 placeholder) for the dynamic part of my website, so I can always pass childImageSharp to the <Img> component of Gatsby.

Here is an example for the fluid image type for featured images on posts:

  • Make sure to include this in your GQL:
featuredImage {
  node {
    sourceUrl
    mediaDetails {
      file
      width
      height
      sizes {
        file
        name
        width
        sourceUrl
      }
    }
  }
}

After loading your posts, send each node of your File nodes (featuredImage) through this function:

/**
 * Attaches a sharped image to the node for Gatsby Image.
 * @param image Dynamic image node to expand.
 * @param maxWidth Real existing width of file to use as default size.
 */
function attachChildImageSharp(
  image,
  maxWidth
) {
  const mediaDetails: IWpMediaDetails = image.mediaDetails;
  if (mediaDetails) {
    maxWidth = maxWidth || mediaDetails.width;
    image.localFile = image.localFile || {};
    image.localFile.childImageSharp = image.localFile.childImageSharp || {};
    const childImageSharp = image.localFile.childImageSharp;

    // only supporting fluid right now:
    const fluid = (childImageSharp.fluid =
      childImageSharp.fluid || {});
    fluid.aspectRatio =
      mediaDetails.width && mediaDetails.height
        ? mediaDetails.width / mediaDetails.height
        : undefined;
    fluid.originalImg = image.sourceUrl;
    fluid.originalName = mediaDetails.file;
    fluid.presentationHeight =
      fluid.aspectRatio && maxWidth
        ? Math.round(maxWidth / fluid.aspectRatio)
        : mediaDetails.height;
    fluid.presentationWidth = maxWidth;
    fluid.sizes = `(max-width: ${maxWidth}px) 100vw, ${maxWidth}px`;

    const srcSets = [];
    const allowedSizes = ["medium", "medium_large", "large"];
    mediaDetails.sizes.forEach((size) => {
      if (allowedSizes.indexOf(size.name) >= 0) {
        if (
          size.width === `${fluid.presentationWidth}`
        ) {
          fluid.src = size.sourceUrl;
        }
        srcSets.push(`${size.sourceUrl} ${size.width}w`);
      }
    });

    fluid.srcSet = srcSets.join(",\n");
  } else {
    console.warn("Unable to attach dynamic image sharp: Missing mediaDetails.");
  }
}

You will call the function like this (also a good spot to attach your generic base64 image):

posts.nodes.forEach((post) => {
  attachChildImageSharp(post.featuredImage.node, 768);
   post.featuredImage.node.localFile.childImageSharp.fluid.base64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQYV2NgYGD4DwABBAEAcCBlCwAAAABJRU5ErkJggg=="; // 1x1 black PNG, from https://shoonia.github.io/1x1/#000000ff
});

Beware that an immutable object will causes errors, so disable caching (fetchPolicy: 'no-cache', in case you use the ApolloClient). Pick a width as 2nd argument that is one of the three widths you selected in the settings of Wordpress for image sizes (not including Thumbnail).

This solution is for Gatsby Image V1 and by all attempts, it's not perfect, but it serves my need.