Context: I have a Next.js site with Chakra UI. I have some user provided markdown content that is fetched from an external source (say, GitHub README.md
for a repo) at runtime.
Now, by default, react-markdown (based on remarkjs) uses the HTML <img>
tag for markdown images (![]()
). I want to use the new <Image />
component released in Next.js 10 in the user provided markdown. Additionally, I also would like to replace other tags with corresponding Chakra UI components.
How do I go about doing this?
SOLUTION
// utils/parser.tsx
import Image from 'next/image';
export default function ImageRenderer({ src, alt }) {
return <Image src={src} alt={alt} unsized />;
}
and then in the required page:
//pages/readme.tsx
import ReactMarkdown from 'react-markdown';
import imageRenderer from '../utils/parser';
// `readme` is sanitised markdown that comes from getServerSideProps
export default function Module({ readme }) {
return <ReactMarkdown allowDangerousHtml={true} renderers={{ image: imageRenderer }} children={readme} />
}
same for other elements...