Last active
March 10, 2020 16:46
-
-
Save 5t3ph/497fc32ca707c9d1706f1298f57543cc to your computer and use it in GitHub Desktop.
Gatsby useStaticQuery to create custom hook for returning an image src path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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