String interpolation in graphQL query

Check the docs for static query

StaticQuery can do most of the things that page query can, including fragments. The main differences are:

  • page queries can accept variables (via pageContext) but can only be added to page components
  • StaticQuery does not accept variables (hence the name “static”), but can be used in any component, including pages

So you might want to query for the image's GatsbyImageSharpFluid in your page query and pass it as the fluid prop directly to gatsby image.


Here is the easy way I ran into:

const Image = props => {
  const data = useStaticQuery(graphql`
    query {
      firstImg: file(relativePath: { eq: "firstImg.png" }) {
        childImageSharp {
          fluid(maxWidth: 300) {
            ...GatsbyImageSharpFluid
          }
        }
      }

      secondImg: file(
        relativePath: { eq: "secondImg.png" }
      ) {
        childImageSharp {
          fluid(maxWidth: 300) {
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  `)

  switch (props.name) {
    case "firstImg":
      return <Img fluid={data.firstImg.childImageSharp.fluid} />
    case "secondImg":
      return <Img fluid={data.secondImg.childImageSharp.fluid} />
    default:
      return <Img />
  }
}

and use it like this:

<Image name="firstImg" />

You can also make it typo-safe by introducing an object with all the images you might want to display, like this:

const Images = { firstImg: 'firstImg', secondImg: 'secondImg' }

and then use it like this:

<Image name={Images.firstImage} />

and

...
switch (props.name) {
case Images.firstImage:
...