Search code examples
graphqlgatsbygatsby-imagedirectusssg

Gatsbyjs + Directus how to get image from content?


I connected gatsby and directus. everything is ok, but...

I have html text field with name "content" in directus, it has images inside. how do i get them in gatsby? enter image description here


Solution

  • I solved the problem as follows:

    1. I created a multiplefiles field in Directus in the Article named "imagelist" there indicated the same images that I use in the article.
    2. Now gatsby gives me an array of images in GraphQL.
    3. Wrote a CustomImage component for the image, where I check the id.
    4. Used the overrides option to replace the img tag in the Markdown component.

    So, my code looks that:

    layout props:

    interface ArticleImage {
      directus_files_id: {
        id: string;
        imageFile: IGatsbyImageData;
      }
    }
    
    interface BlogLayoutProps {
      title: string;
      annotation: string;
      imageData: IGatsbyImageData;
      allImages: Array<ArticleImage>;
      content: string;
    }
    

    custom image component:

    const CustomImage = (props) => {
    
        const { alt, width, height, src } = props;
        const image = allImages.find(i => src.indexOf(i.directus_files_id.id) !== -1);
    
        if (image) {
          const imgData = getImage(image.directus_files_id.imageFile);
          imgData.width = +width;
          imgData.height = +height;
          return <GatsbyImage image={imgData} alt={alt}/>;
        }
    
        return <img src={src} width={width} height={height} alt={alt} />
      };    
    

    in layout component:

    <StyledContent>
          <Markdown
            options={{
              overrides: {
                img: {
                  component: CustomImage,
                }
              }
            }}
          >
            {content}
          </Markdown>
        </StyledContent>
    

    query in page:

    query MyQuery {
      directus {
        article_by_id(id: "26434049-7bb4-46d3-8ad1-c04973b9cf71") {
          id
          category {
            id
            title
          }
          title
          description
          content
          image {
            id
            width
            height
            imageFile {
              childImageSharp {
                gatsbyImageData
              }
            }
          }
          imagelist {
            directus_files_id {
              id
              imageFile {
                childImageSharp {
                  gatsbyImageData
                }
              }
            }
          }
        }
      }
    }
    

    I hope someone will help my solution or push him to new thoughts!