Skip to content

[gatsby-source-contentful]: Rendering inline asset hyperlinks #28074

@martynhoyer

Description

@martynhoyer

I'm in the process of upgrading gatsby-source-contentful and running into some issues rendering out asset hyperlinks within a rich text block.

Previously I had this code, which formed the options object I would pass to the old documentToReactComponents function:

const richTextOptions = {
  renderNode: {
    [INLINES.ASSET_HYPERLINK]: function assetHyperlink(node, children) {
      const locale = "en-US";
      const { nodeType, data } = node;
      const url = data.target.fields.file[locale].url;
      switch (nodeType) {
        case "asset-hyperlink":
          return (
            <a href={url} download>
              {children}
            </a>
          );
        default:
          console.warn(nodeType + " not set");
      }
    },
  },
};

I've refactored this to the following:

const richTextOptions = {
  renderNode: {
    [INLINES.ASSET_HYPERLINK]: (node, children) => {
      console.log('node', node)
      return <a href={'#'} download>{children}</a>
    },
  },
};

But when I log out the node object, there's nothing in there to get the URL. node.data.target.sys.id gives me the Contentful ID of the asset, but I'm not sure how I can use that to get the file URL.

I've seen the examples on the Changelog and thought I'd try the new references object in the GraphQL query, but I can't figure out how that works...

If I try it in GraphiQL, like this:

    body {
      raw
      references {
        ... on ContentfulAsset {
          contentful_id
          file {
            url
          }
        }
      }
    }

I can get the URL, and I sort of expected that to become available to me in the rich text options, If I add that in, then my node object changes and node.data becomes an empty object.

Is that right? Is it a bug? Or can someone help me do the right thing?!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions