I've been searching for this answer as well. Hopefully this answers your question:
The final code:
import React from 'react';
import { StaticQuery, graphql } from 'gatsby';
import Img from 'gatsby-image';
// Note: You can change "images" to whatever you'd like.
const Image = props => (
<StaticQuery
query={graphql`
query {
images: allFile {
edges {
node {
relativePath
name
childImageSharp {
fluid(maxWidth: 600) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`}
render={data => {
const image = data.images.edges.find(n => {
return n.node.relativePath.includes(props.filename);
});
if (!image) {
return null;
}
//const imageSizes = image.node.childImageSharp.sizes; sizes={imageSizes}
return <Img alt={props.alt} fluid={image.node.childImageSharp.fluid} />;
}}
/>
);
export default Image;
Using the image:
import Image from '../components/Image';
<div style={{ maxWidth: `300px` }}>
<Image alt="Gatsby in Space" filename="gatsby-astronaut.png" />
</div>
Explanation
Because StaticQuery doesn't support string interpolation in its template literal, we can't really pass it any props. Instead we will try and handle check for props in the StaticQuery's Render portion.
Caveats
I'm not 100% sure if this affects compiling time since we are scanning all images. If it does, please let me know!
Update: If you have many images, bundle size can get quite large as this solution does scan ALL images.
Further customization
You can adjust the code to show a placeholder image if no props are passed.
Alternatives
That said, there is another way you could tackle this but with a bit more work/code.
Sources
- I modified the code from this article. (Please note that the article was using deprecated code.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…