Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 = ({img}) => {
* const imgSrc = useImgSrc(img);
*
* return (
* <img src={imgSrc} />
* )
* }
*
* <Image img="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
You can’t perform that action at this time.