Richard Reis
Richard Reis

Reputation: 239

On Gatsby, how to do a GraphQL query using a prop?

I'm passing a prop to a new component and trying to use that to do a graphql query. It looks like this.

import React from "react"
import { graphql, useStaticQuery } from "gatsby"
import Img from "gatsby-image"

const ComponentName = props => {
  const getImage = graphql`
{
  image: file(relativePath: { eq: ${props.img} }) {
    childImageSharp {
      fluid {
        ...GatsbyImageSharpFluid
      }
    }
  }
}
`
  const data = useStaticQuery(getImage)
  return (
    <li>
      <Img
        fluid={data.image.childImageSharp.fluid}
      />
    </li>
  )
}

export default ComponentName

But I'm getting this error BabelPluginRemoveGraphQLQueries: String interpolations are not allowed in graphql fragments. Included fragments should be referenced as...MyModule_foo.

I've tried all sorts of different tricks to get rid of the "string interpolation" error. But none of them work (it just shows a different error each time).

I'm assuming you can't do a graphql query using props? Or is there another way to do this?

Upvotes: 4

Views: 1144

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53874

From StaticQuery docs:

StaticQuery does not accept variables (hence the name “static”), but can be used in any component, including pages.

And same for the hook version useStaticQuery:

useStaticQuery does not accept variables (hence the name “static”), but can be used in any component, including pages.

You can read further in gatsby's GitHub here.

Upvotes: 5

Related Questions