3

I am using Gatsby as the starter for my react app. To handle content I am using Contentful.

In my Contentful Content Model, I've created the following content types:

  • Short Text
  • Short Text
  • Media
  • Rich Text
  • Rich Text

Using Gatsby's gatsby-source-contenful and @contentful/gatsby-transformer-contentful-richtext plugins, I've successfully rendered my all of these content types, except in my Rich Text types I'm not able to render the Embedded Assets within it.

I've tried installing @contentful/rich-text-types via npm and using the constants MARK and INLINES based on the example in Gatsby's documentation found here

const { MARKS, INLINES } = require('@contentful/rich-text-types')
{
      resolve: `@contentful/gatsby-transformer-contentful-richtext`,
      options: {
        renderOptions: {
          /*
           * Defines custom html string for each node type like heading, embedded entries etc..
           */
          renderNode: {
            // Example
            [INLINES.ASSET_HYPERLINK]: node => {
              return `<img class='custom-asset' src="${
                node.data.target.fields.file['en-US'].url
              }"/>`
            },
            [INLINES.EMBEDDED_ENTRY]: node => {
              return `<div class='custom-entry' />${
                node.data.target.fields.name['en-US']
              }</div>`
            },
          },
          /*
           * Defines custom html string for each mark type like bold, italic etc..
           */
          renderMark: {
            // Example
            [MARKS.BOLD]: text => `<strong>${text}<strong>`,
          },
        },
      },
    },

Ideally, I'd like for Gatbsy to automatically render image assets within the Rich Text types as <img src="[ASSET URL]" alt="[ASSET DESCRIPTION]">

Ryan Brooks
  • 101
  • 2
  • 8

1 Answers1

5

Try this:

const { BLOCKS } = require('@contentful/rich-text-types')
...
renderNode: {
  [BLOCKS.EMBEDDED_ASSET]: node => {
    // console.log(node)
    let { description, title, file } = node.data.target.fields
    // console.log(file["en-US"].url)
    return <img src={file["en-US"].url} />
  },
},

This seems to work for me, although the image seems to be full-size, and load rather slowly. Needs additional work, but this does seem to work (at least in development)

EDIT:
It seems like the fields property on my node.data.target stopped appearing when I send my graphql query... and this stopped working... super bizarre

EDIT 2: if you delete the .cache folder (project-root/.cache), the above issue gets fixed. https://github.com/gatsbyjs/gatsby/issues/10592

Kevin Wang
  • 644
  • 1
  • 8
  • 20
  • Adding `forceFullSync: true` to `gatsby-source-contentful` options in `gatsby-config.js` solves the issue with .cache – Saša Šijak Nov 12 '19 at 11:14