menu

Gatsby

Fast in every way that matters. Gatsby is a free and open source framework based on React that helps developers build blazing fast websites and apps.

Channels
# All channels
view-forward
# General
view-forward
# I Made This
view-forward
# Meta
view-forward
# Themes
view-forward
Team

Using Variables in a StaticQuery

December 13, 2018 at 10:05pm

Using Variables in a StaticQuery

December 13, 2018 at 10:05pm
Hey Folks - I'm using gatsby-image in my latest project and I'm finding it a bit cumbersome to have to write a whole query just to display an image. I would love to just have a component that I pass a src to and it does it all under the hood.
So - I'm writing a component with StaticQuery that looks like this:
import React from 'react';
import Img from 'gatsby-image';
import { StaticQuery, graphql } from 'gatsby';
function renderImage({ file }) {
return <Img fluid={file.childImageSharp.fluid} />
}
const MyImg = function (props) {
return <StaticQuery
query={graphql`
query {
file(relativePath: { eq: "wes-and-scott.jpg" }) {
childImageSharp {
fluid(maxWidth: 1000) {
...GatsbyImageSharpFluid
}
}
}
}
`}
render={renderImage}
/>
}
export default MyImg;
Now that works amazingly well, BUT I can't make the filename dynamic.
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.
I tried string interpolation and that doesn't work.
Any way to get around this? Am I thinking about this in the wrong way?

December 13, 2018 at 10:16pm
Hey Wes — definitely agree that allowing components w/ StaticQuerys take arguments would be amazing. This isn't something we've yet tackled but it should be doable with sufficient babel/code analysis magic :-)
  • reply
  • like
One constraint would be that variables passed to these components would still need to be "static" meaning they're numbers/strings.
like-fill
5
  • reply
  • like
I have not used gatsby, but I think you can hack the graphql. This is something untested though:
import React from 'react';
import Img from 'gatsby-image';
import { StaticQuery, graphql } from 'gatsby';
function renderImage({ file }) {
return <Img fluid={file.childImageSharp.fluid} />
}
const MyImg = function (props) {
function hackTheQuery(src) {
return `
query {
file(relativePath: { eq: "${src}" }) {
childImageSharp {
fluid(maxWidth: 1000) {
...GatsbyImageSharpFluid
}
}
}
}
`
}
return <StaticQuery
query={graphql([hackTheQuery(props.src)])}
render={renderImage}
/>
}
export default MyImg;
  • reply
  • like
Show more messages