Skip to content

Instantly share code, notes, and snippets.

@solace
Created March 18, 2022 06:16
Show Gist options
  • Save solace/589b178b6454c3c640105cee3af4d4dd to your computer and use it in GitHub Desktop.
Save solace/589b178b6454c3c640105cee3af4d4dd to your computer and use it in GitHub Desktop.
Rendering Contentful embedded assets and entries in GatsbyJS
import { documentToReactComponents } from '@contentful/rich-text-react-renderer';
import { graphql } from 'gatsby';
import React from 'react';
// Custom renderer for embedded content which accepts `body` / `references` from the graphql query.
// Search `references` for the embedded object ID for full access to nested content.
const rendererOptions = (references) => ({
renderNode: {
[BLOCKS.EMBEDDED_ASSET]: (node) => {
const imageID = node.data.target.sys.id;
const {
file: {url},
title
} = references.find(({contentful_id: id}) => id === imageID);
return <img src={url} alt={title} />;
},
[BLOCKS.EMBEDDED_ENTRY]: (node) => {
const entryID = node.data.target.sys.id;
const { title, slug } = references.find(({contentful_id: id}) => id === entryID);
return <a href={`/${slug}`}>{title}</a>;
},
},
});
const Post = ({ data }) => {
const { post } = data;
return (
<article>
{documentToReactComponents(
JSON.parse(post.body.raw),
rendererOptions(post.body.references)
)}
</article>
);
};
export default Post;
// Include all required fields for the content references. For GatsbyJS at the least, `contentful_id` and `__typename` are required.
export const query = graphql`
query Post($id: String) {
post: contentfulBlog(id: { eq: $id }) {
body {
raw
references {
... on ContentfulAsset {
contentful_id
__typename
title
file {
url
}
}
... on ContentfulArticle {
contentful_id
__typename
title
slug
}
}
}
}
}
`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment