Skip to content

Instantly share code, notes, and snippets.

@emmiep
Created June 29, 2021 18:48
Show Gist options
  • Save emmiep/b83b7933f54d0f1d923281362088c8eb to your computer and use it in GitHub Desktop.
Save emmiep/b83b7933f54d0f1d923281362088c8eb to your computer and use it in GitHub Desktop.
GraphCMS image loader for Next.js example
// 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