Created
June 29, 2021 18:48
-
-
Save emmiep/b83b7933f54d0f1d923281362088c8eb to your computer and use it in GitHub Desktop.
GraphCMS image loader for Next.js example
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
// GraphQL query | |
const GetPhotos = gql` | |
query GetPhotos { | |
assets { | |
id | |
url | |
width | |
height | |
} | |
} | |
`; | |
// render function | |
const Home = ({photos}) => ( | |
<> | |
{photos.map((photo) => ( | |
<div key={photo.id}> | |
<Image | |
src={photo.url} | |
width={photo.width} | |
height={photo.height} | |
layout="responsive" | |
loader={graphCmsLoader} /> | |
</div> | |
))} | |
</> | |
); | |
export default Home; | |
// loader implementation | |
function graphCmsLoader({src, width}) { | |
const match = /^(https?:\/\/media.graphcms.com)(?:\/[^\/]+)?\/([^\/]+)$/.exec(src); | |
if (!match) { | |
throw new Error('Invalid GraphCMS asset URL'); | |
} | |
const [prefix, handle] = match.slice(1); | |
const resizedSrc = `${prefix}/resize=width:${width}/${handle}`; | |
return resizedSrc; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment