This example demonstrates how to use gatsby-image with GraphCMS assets.
• Demo
Gatsby nodes are not automatically created for GraphCMS assets when using gatsby-source-graphql. This limitation will prevent you from using gatsby-image with your GraphCMS project out of the box.
We're able to work around this by combining the createReolvers API and gaby-source-filesyetem library.
This will enable us to manually create local nodes for our GraphCMS assets at build time.
We need to extend the base GraphCMS_Asset type to include a new node field. This field will resolve to a newly created local file node, built from createRemoteFileNode() by passing the URL of the GraphCMS asset.
// gatsby-node.js
const { createRemoteFileNode } = require('gatsby-source-filesystem');
exports.createResolvers = ({
actions: { createNode },
cache,
createNodeId,
createResolvers,
store,
reporter,
}) => {
const resolvers = {
GraphCMS_GraphCmsAsset: {
node: {
type: `File`,
resolve: ({ url }, args, context, info) => {
return createRemoteFileNode({
url,
store,
cache,
createNode,
createNodeId,
reporter,
});
},
},
},
};
createResolvers(resolvers);
};We can now query for the node field and use the available gatsby-transformer-sharp fragments to achieve the desired effects.
Note: Our query must also include the
urlfield as this is used in ourcreateResolvers()function to fetch and build the local asset node.
Combine this with the <Img /> component and we can utilise all the benefits of gatsby-image with our remote GraphCMS assets!
import React from 'react';
import { graphql, useStaticQuery } from 'gatsby';
import Img from 'gatsby-image';
const pageQuery = graphql`
{
gcms {
graphcms {
products {
image {
url
node {
childImageSharp {
fluid(maxWidth: 560) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
}
}
`;
const IndexPage = () => {
const {
gcms: { graphcms: { products } },
} = useStaticQuery(pageQuery);
return products.map((product) => (
<Img fluid={product.image.node.childImageSharp.fluid} />
));
};
export default IndexPage;npx create-gcms-app with-gatsby-imageInstall & Run:
cd with-gatsby-image
npm install
npm run dev
# or
cd with-gatsby-image
yarn
yarn dev