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?
I solved the problem as follows:
CustomImage
component for the image, where I check the id.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!