Eric Johnson
Eric Johnson

Reputation: 1144

How to get Gatsby Images based on results of PageQuery?

I'd like to do something like the following so I can get Gatsby Images dynamically:

const image = 'gastby-astronaut.png';

export const imageQuery = graphql`
  { allImageSharp (
    filter: {
      fluid: {
        originalName: {
          regex: "/${image}/"
        }
      }
    }
  ){
  edges { 
    node {
      fluid {
        originalName
      }
    }
  }
}
}
`;

However, I can't figure out how to connect this query to an initial query that would get the 'gatsby-astronaut.png', or perform this query from a subcomponent with a . I get this error when I try this:

Error: BabelPluginRemoveGraphQL: String interpolations are not allowed 
in graphql fragments. Included fragments should be referenced as
 `...MyModule_foo`.

Any suggestions on the proper way to return Gatsby Images dynamically?

Upvotes: 3

Views: 1972

Answers (2)

coreyward
coreyward

Reputation: 80041

Ah, yeah Gatsby extracts GraphQL queries from your pages through static analysis: they load the file as text, parse it, and extract the query, all before the actual file gets executed. This means that your typical tagged-template literal functionality isn't there.

The only way to filter is through context provided when createPage is called from gatsby-node.js. I.e. if you do this:

exports.createPages = ({ graphql, actions }) =>
  graphql(`some query here`).then(result => {
    actions.createPage({
      path: "/output-path/",
      component: path.resolve(`./src/templates/your_template.jsx`),
      context: { image: result.data.yourImage },
    })
  })

Then you can do this in your page query:

query SomePage($image: String!) {
  allImageSharp (
    filter: {
      fluid: {
        originalName: {
          regex: $image
        }
      }
    }
  ){
    edges { 
      node {
        fluid {
          originalName
        }
      }
    }
  }
}

Upvotes: 4

Eric Johnson
Eric Johnson

Reputation: 1144

Here's a solution I came up with... pretty janky, but it works:

import PropTypes from 'prop-types';
import React from 'react';
import Img from 'gatsby-image';
import { useStaticQuery, graphql } from 'gatsby';


const Image = ({ imageYouWant }) => {
  const data = useStaticQuery(
    graphql`
      query allTheImagesQuery{
        allImageSharp {
          edges {
            node {
              fluid(maxWidth:1000) {
                ...GatsbyImageSharpFluid
                originalName
              }
            }
          }
        }
      }`,
  );

  const TheImageYouWant = data.allImageSharp.edges
    .filter(edge => edge.node.fluid.originalName === imageYouWant)
    .map(myImage => <Img fluid={myImage.node.fluid} />);

  return (
    <>
      { TheImageYouWant }
    </>
  );
};


Image.propTypes = {
  imageYouWant: PropTypes.string,
};

Image.defaultProps = {
  imageYouWant: '',
};

export default Image;

Upvotes: 3

Related Questions