rich-text icon indicating copy to clipboard operation
rich-text copied to clipboard

Responsive images with gatsby-source-contentful rich text and gatsby-image

Open marcuslindfeldt opened this issue 6 years ago • 3 comments

I'm unable to use gatsby-image in combination with Contentful rich text queried via gatsby-source-contentful because the graphql schema for contentful that gatsby generates does not allow me to query an embedded asset in rich text as I would if I just query a single asset.

I created an issue in the gatsby repo (https://github.com/gatsbyjs/gatsby/issues/14338) describing this issue but maybe it's more appropriate here.

marcuslindfeldt avatar May 27 '19 16:05 marcuslindfeldt

Hey @marcuslindfeldt

StaticQuery would have been an optimal solution, unfortunately, it doesn't support variables.

But you could do the following by querying allContentfulAsset and later filtering by id.

import React from "react"
import { graphql, useStaticQuery } from "gatsby"
import Image from "gatsby-image"

// Gatsby adds 'c' to entity id if it starts with a number.
function fixId(id) {
  if (id.length === 23 && id.startsWith("c")) {
    return id.slice(1)
  }
}

export const ContentfulFixedAsset = ({ contentfulId }) => {
  const data = useStaticQuery(graphql`
    query {
      allContentfulAsset {
        edges {
          node {
            contentful_id
            fixed {
              base64
              tracedSVG
              aspectRatio
              width
              height
              src
              srcSet
              srcWebp
              srcSetWebp
            }
          }
        }
      }
    }
  `)

  const image = data.allContentfulAsset.edges.find(
    edge => edge.node.contentful_id === fixId(contentfulId)
  )

  return <Image fixed={image.node.fixed} />
}
export default ContentfulFixedAsset

sbezludny avatar Jun 01 '19 07:06 sbezludny

@sbezludny This would probably work but this solution will query all assets on contentful right for in my case every blog post that gatsby builds? Is it not possible to query only the assets related to the rich text field or the content model?

marcuslindfeldt avatar Jun 02 '19 20:06 marcuslindfeldt

this solution will query all assets on contentful right for in my case every blog post that gatsby builds?

No additional api calls will be made. AFAIK, Gatsby uses sync API under the hood, which means that all the assets are already available on the client side all the time.

Is it not possible to query only the assets related to the rich text field or the content model?

No, querying to the rich text is not possible at the moment.

sbezludny avatar Jun 03 '19 09:06 sbezludny