Skip to content

Instantly share code, notes, and snippets.

@5t3ph
Last active March 10, 2020 16:46
Show Gist options
  • Save 5t3ph/497fc32ca707c9d1706f1298f57543cc to your computer and use it in GitHub Desktop.
Save 5t3ph/497fc32ca707c9d1706f1298f57543cc to your computer and use it in GitHub Desktop.
Gatsby useStaticQuery to create custom hook for returning an image src path
/**
* Required plugins: gatsby-source-filesystem and gatsby-plugin-sharp
*
* Basic Hook Usage:
*
* import useImgSrc from '../utils/useImgSrc';
*
* const Image = ({src}) => {
* const imgSrc = useImgSrc(src);
*
* return (
* <img src={imgSrc} />
* )
* }
*
* <Image src="example.png" />
*/
import { graphql, useStaticQuery } from 'gatsby';
interface IImgSharp {
node: {
fluid: {
src: string;
};
};
}
const useImgSrc = (img: string) => {
const { allImageSharp } = useStaticQuery(
graphql`
query {
allImageSharp {
edges {
node {
fluid {
src
}
}
}
}
}
`,
);
const imgSrc = allImageSharp.edges.filter((image: IImgSharp) => {
return image.node.fluid.src.includes(img);
});
return imgSrc[0].node.fluid.src;
};
export default useImgSrc;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment