String interpolation in graphQL query

一笑奈何 提交于 2019-12-13 17:30:26

问题


I am new to Gatsby and its graphQL query system to retrieve assets. I have a working component Image that fetches an image and displays it. I want to have the name of the image customizable but I can't figure out how to dit.

Here is the working component:

const Image = () => (
  <StaticQuery
    query={graphql`
      query {
        // fetching the image gatsby-astronaut.png
        placeholderImage: file(relativePath: { eq: "gatsby-astronaut.png" }) {
          childImageSharp {
            fluid(maxWidth: 300) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    `}
    render={data => <Img fluid={data.placeholderImage.childImageSharp.fluid} />}
  />
);

And here is what I tried to have a customizable image:

const Image = ({ imgName }: { imgName: string }) => (
  <StaticQuery
    query={graphql`
      query {
        // fetching the image imgName
        placeholderImage: file(relativePath: { eq: "${imgName}.png" }) {
          childImageSharp {
            fluid(maxWidth: 300) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    `}
    render={data => <Img fluid={data.placeholderImage.childImageSharp.fluid} />}
  />
);

But it raises the following error for the query:

Expected 1 arguments, but got 2.ts(2554)

How can I have a customizable image name?


回答1:


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.




回答2:


Using ksav answer I managed to make this work by using pageQuery and receive the images i want to use in a specific page through props.

Like this:

export const pageQuery = graphql`
  coverImage: file(relativePath: { eq: "coverImage.png" }) {
    childImageSharp {
      fluid(maxWidth: 600) {
        ...GatsbyImageSharpFluid_tracedSVG
      }
    }
  }
}`

If you add this to your page component you will receive the props coverImage with the coverImage.png image. Hope this helps!



来源:https://stackoverflow.com/questions/56118471/string-interpolation-in-graphql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!