3

I'm learning Gatsby by building a blog using Contentful as CRM and I'm in doubt how to use it together with gatsby-images to show images into the body of a rich-text field, been searching the internet and still didn't found a good example on how to do it.

My post.jsx:

import React from 'react';
import { graphql } from 'gatsby';
import { documentToReactComponents } from '@contentful/rich-text-react-renderer';

import Layout from '../components/layout';
import Image from '../components/image';

const renderBody = documentToReactComponents;

export const query = graphql`
  query($slug: String) {
    contentfulBlogPost(slug: { eq: $slug }) {
      title
      author
      date(formatString: "DD-MM-YYYY")
      /** body is my rich-text field*/
      body {
        json
      }
    }
  }`;

const Post = ({ data }) => {
  const {
    title,
    author,
    date,
    body: { json },
  } = data.contentfulBlogPost;

  const options = {
    renderNode: {
      'embedded-asset-block': (node) => {
        console.log(`Node: ${JSON.stringify(node, undefined, 2)}`);
        /** It works with no problems when using a simple img html tag */
        const src = node.data.target.fields.file['en-US'].url;
        const imageAlt = node.data.target.fields.file['en-US'].title;
        return (
          <Image alt={imageAlt} fluid={???}/>
        );
      },
    },
  };

  return (
    <Layout>
      <article>
        <h1>{title}</h1>
        <p>Author: {author}</p>
        <p>Date: {date}</p>
        { renderBody(json, options) }
      </article>
    </Layout>
  );
};

export default Post;

I've been playing with GraphiQL for at least an entire day and still didn't figured it out where and how to use GatsbyContentfulFluid together with the rich-text field as described into the plugin's page.

1 Answers1

0

I got my images issues sorted by using the downloadLocal: true in Gatsby-config.js:

{
    resolve: `gatsby-source-contentful`,
    options: {
            spaceId: process.env.CONTENTFUL_SPACE_ID,
            // Learn about environment variables: https://gatsby.dev/env-vars
            accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
            downloadLocal: true,
        },
    },

which caused Gatsby to expose a bunch of extra attributes in the JSON returned by body { json } which were not previously being fetched.

I'm not using fluid (yet) but the folks on this thread are:

https://github.com/contentful/rich-text/issues/70

Sez
  • 1,275
  • 11
  • 26