Skip to content

Latest commit

 

History

History
 
 

with-gatsby-image

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 

GraphCMS ⨯ Gatsby Image

Join our Slack

This example demonstrates how to use gatsby-image with GraphCMS assets.

Demo

Deploy with Vercel

Why?

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.

How?

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 url field as this is used in our createResolvers() 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;

How to Use

Download Manually

npx create-gcms-app with-gatsby-image

Install & Run:

cd with-gatsby-image
npm install
npm run dev
# or
cd with-gatsby-image
yarn
yarn dev

Run on Codesandbox

Develop with Codesandbox