Can I use gatsby-plugin-image for a dynamic image path?

Viewed 2892

I am fetching data that contains a path to a users profile picture. Can I use gatsby-plugin-image to render this image or is that not possible using this plugin?

Specifically, after an api call I get data returned like this;

data:{
 user:{
  profilePicture: "https://mywebsite/img.jpg"
     }
    }
   }

Following the documentation, it appears that using StaticImage is not appropriate since I would have to pass in src as a prop (see example below). However, using GatsbyImage (or getSrc or getImage) returns undefined and also does not appear to be how this plugin was intended to be used. Is there another pattern that I am missing or is this use case not a correct use of gatsby-plugin-image?

<StaticImage src={data.user.profilePicture} alt={data.user.fullname} />

returns: No data found for image "undefined"

1 Answers

As you can see in the Gatsby image documentation, StaticImage component can't receive external props. So this will work:

 <StaticImage src="https://mywebsite/img.jpg" alt="" />

But this won't:

 <StaticImage src={data.user.profilePicture} alt="" />

This is because Gatsby will download the image in the build-time.

To use GatsbyImage (to create dynamic images) you need to store the images locally and tell Gatsby, via the filesystem, where are they located to allow Gatsby to use its transformers and sharps to that image, what will create a queryable GraphQL node. This will allow you to query them like:

import { graphql } from "gatsby"
import { GatsbyImage, getImage } from "gatsby-plugin-image"

function BlogPost({ data }) {
 const image = getImage(data.blogPost.avatar)
 return (
   <section>
     <h2>{data.blogPost.title}</h2>
     <GatsbyImage image={image} alt={data.blogPost.author} />
     <p>{data.blogPost.body}</p>
   </section>
 )
}

export const pageQuery = graphql`
 query {
   blogPost(id: { eq: $Id }) {
     title
     body
     author
     avatar {
       childImageSharp {
         gatsbyImageData(
           width: 200
           placeholder: BLURRED
           formats: [AUTO, WEBP, AVIF]
         )
       }
     }
   }
 }
`

You can check https://www.gatsbyjs.com/plugins/gatsby-plugin-image/#dynamic-images for more details.

Related