I’m thinking of using Gatsby-Image for my next project and have 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 <Image /> tag from Gatsby much like a regular <img src”image.png”>
tag. How can I make the Gatsby <Image /> 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
// receive the 'src' value as a property?
//
// It returns a StaticQuery component with a query property
// and render property. The query property has the GraphQL
// query to receive the images and render prop returns a
// renderImage function which in return, returns an Img
// component from 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 property in each Gatsby <Image /> and match it with all my images in my assets file and then display it. Is this even possible with <StaticQuery />?
I read in the documentation that StaticQuery 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.
This is an example: https://codesandbox.io/s/py5n24wk27