Preview Component
The Preview
component is responsible for rendering the Markdown content into HTML, providing a live preview of the user's document.
Props
markdown: string
: The Markdown string that needs to be rendered.
Key Libraries
The component leverages the react-markdown
library and several plugins to handle the conversion from Markdown to HTML safely and effectively.
react-markdown
: The core library that parses Markdown and renders it as React components.remark-gfm
: A plugin that adds support for GitHub Flavored Markdown (GFM), which includes features like tables, strikethrough, task lists, and autolink literals.rehype-raw
: A plugin that allows rendering of raw HTML found within the Markdown. This is necessary for users who want to embed custom HTML, but it also introduces security risks if the content is not sanitized.rehype-sanitize
: A crucial security plugin that sanitizes the HTML output. It parses the HTML and removes any potentially malicious code (like<script>
tags), preventing Cross-Site Scripting (XSS) attacks. It works in conjunction withrehype-raw
to allow safe HTML rendering.
Styling
The preview pane is styled using Tailwind CSS's typography plugin (@tailwindcss/typography
).
prose
: This class applies beautiful typographic defaults to the rendered HTML. It styles headings, paragraphs, lists, blockquotes, and other elements to be highly readable.prose-zinc
: A color scheme modifier for the prose styles.dark:prose-invert
: This inverts the color scheme of the typography when the application is in dark mode, ensuring text remains legible.max-w-none
: By default, theprose
class sets amax-width
to contain the text for better readability.max-w-none
removes this constraint, allowing the preview to fill its container.
Code Breakdown
import ReactMarkdown from 'react-markdown';
import rehypeRaw from 'rehype-raw';
import rehypeSanitize from 'rehype-sanitize';
import remarkGfm from 'remark-gfm';
interface PreviewProps {
markdown: string;
}
const Preview: React.FC<PreviewProps> = ({ markdown }) => {
return (
<div className="h-full overflow-auto p-6 prose prose-zinc dark:prose-invert max-w-none">
<ReactMarkdown
rehypePlugins={[rehypeRaw, rehypeSanitize]}
remarkPlugins={[remarkGfm]}
>
{markdown}
</ReactMarkdown>
</div>
);
};
export default Preview;
- The component receives the
markdown
string as a prop. - It renders a
div
that acts as a scrollable container for the preview content. - The
ReactMarkdown
component takes themarkdown
string as its child and applies the configuredremark
andrehype
plugins to process and render it.