I’m using React, Astro and Contenful. I need to render rich text with images. I tried to use documentToReactComponents function from Contentful’s @Contentful/rich-text-react-renderer package to render rich text content in my React application. While my text and headings are rendering correctly, any images within the content do not appear.
Here’s a simplified version of my component:
import React, { useState } from "react";
import { documentToReactComponents } from "@Contentful/rich-text-react-renderer";
import type { QuestionAndAnswerItem } from "../types/contentful";
interface TrendingArticlesProps {
faqData: QuestionAndAnswerItem[];
heading: string;
}
export const TrendingArticles: React.FC<TrendingArticlesProps> = ({ faqData, heading }) => {
const [openIndex, setOpenIndex] = useState<number | null>(null);
const handleToggle = (index: number) => {
setOpenIndex((prevIndex) => (prevIndex === index ? null : index));
};
return (
<section style={{ margin: "2rem 0" }}>
<h2>{heading}</h2>
<div>
{faqData.map((item, index) => (
<div
key={index}
style={{
border: "1px solid #ccc",
borderRadius: "4px",
marginBottom: "0.5rem",
}}
>
<button
onClick={() => handleToggle(index)}
style={{
width: "100%",
textAlign: "left",
padding: "1rem",
background: "F9F9F9_1",
border: "none",
cursor: "pointer",
}}
>
{documentToReactComponents(item.question)}
</button>
{openIndex === index && (
<div style={{ padding: "1rem", background: "#fff" }}>
{documentToReactComponents(item.answer)}
</div>
)}
</div>
))}
</div>
</section>
);
};
documentToReactComponents function from Contentful’s @Contentful/rich-text-react-renderer package to render rich text content in my React application. While my text and headings are rendering correctly, any images within the content do not appear.
contentful content
output
