shadcn.io is an independent project built on shadcn/ui
On this page8 sections
Markdown reaches your app as a string: a model's reply, a README, a field from your CMS. TanStack Markdown (opens in a new tab) turns that string into React elements, and our components style what it renders: Prose for an article, Code Block for fenced code, Message for a chat reply.
There's no Markdown component to install. This guide builds two small files you own: an Article for Markdown you trust, and a MarkdownReply for model output that streams in and may contain anything.
An answer written a word at a time. Its paragraphs and inline code render through TanStack Markdown, the fenced hook becomes a Code Block titled with its language, and the copy button stays off until the closing fence arrives. Replay streams it again.
Install
bun add @tanstack/markdownTanStack Markdown 1.0 has no runtime dependencies. Each part is its own entry point: the parser in @tanstack/markdown/parser, the React renderer in @tanstack/markdown/react, an HTML renderer in @tanstack/markdown/html, and optional extensions under @tanstack/markdown/extensions/….
Then add the two components the output is drawn with:
Code Block's install also adds the useHighlightedCode hook, in hooks/use-highlighted-code.ts, and the highlighter it runs on. The code on this page uses TanStack Markdown 1.0 and the components on Base UI.
Render Markdown you trust
A README, a changelog or a CMS field is written by your team, so it can go straight in. Markdown takes the string as its child and renders a fragment, with no wrapper of its own, so the element around it is yours. Make it Prose, and every heading, list, table, quote and code span takes the article styles without a class of its own.
import { parseMarkdown } from "@tanstack/markdown/parser";
import { Markdown } from "@tanstack/markdown/react";
import { Prose } from "@/components/ui/prose";
export function Article({ source }: { source: string }) {
const document = parseMarkdown(source);
return (
<Prose>
<Markdown headingAnchors>{document}</Markdown>
</Prose>
);
}- It renders on the server.
Markdownuses no hooks, so a Server Component can render it and the page ships as HTML.Markdownalso takes a string directly; parsing first withparseMarkdownlets you parse once, at build time or from a cache, since the document is plain data. - Front matter comes out. A leading
---block isn't rendered. Its raw text is ondocument.frontmatter, unparsed, for your own YAML parser. Passfrontmatter: falsetoparseMarkdownto render it as Markdown instead. - Headings get ids. Each heading has a stable
id, unique on the page, andheadingAnchorsadds a#link inside it, hidden from screen readers and out of the tab order. - The measure stays readable. Prose caps its width at
37emand centers itself. Give itclassName="max-w-none"to fill its container.
A heading, two paragraphs and a Code Block inside Prose. The article styles reach the elements around the block, and the block keeps its own surface, spaced like a paragraph. Markdown rendered into Prose gets the same treatment.
For text you write element by element in JSX, use Typography classes instead.
Map elements to your components
components swaps the element TanStack Markdown would render for one of yours, by tag name. Known tags get their props typed: a receives anchor props and img image props.
import type { MarkdownComponents } from "@tanstack/markdown/react";
const EXTERNAL = /^https?:\/\//i;
export const components = {
a({ children, href, ...props }) {
const external = EXTERNAL.test(href ?? "");
return (
<a
{...props}
href={href}
rel={external ? "noreferrer" : props.rel}
target={external ? "_blank" : props.target}
>
{children}
{external ? <span className="sr-only"> (opens in a new tab)</span> : null}
</a>
);
},
img({ alt, ...props }) {
return <img {...props} alt={alt ?? ""} decoding="async" loading="lazy" />;
},
} satisfies MarkdownComponents;<Markdown components={components}>{source}</Markdown>A mapping applies everywhere that tag is rendered. A code entry replaces inline code and also the <code> inside every fenced block, so it can't tell the two apart. To put fences in a Code Block, render the blocks yourself, as the next section does.
Render model output
A model's reply differs from a README in three ways: it streams in, it often contains code, and it's untrusted. One component handles all three. It parses the text with the streaming extension, sends each top-level fence to a Code Block, and renders every other block with renderBlockReact, the same function Markdown uses inside.
"use client";
import { streamingMarkdownExtension } from "@tanstack/markdown/extensions/streaming";
import { parseMarkdown } from "@tanstack/markdown/parser";
import {
type MarkdownComponents,
renderBlockReact,
} from "@tanstack/markdown/react";
import type { ComponentProps } from "react";
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/components/ui/code-block";
import { useHighlightedCode } from "@/hooks/use-highlighted-code";
const extensions = [streamingMarkdownExtension()];
const FENCE = /^```/gm;
// The start of a closing fence that hasn't fully arrived.
const PARTIAL_FENCE = /\n`{1,3}$/;
const components = {
code: (props: ComponentProps<"code">) => (
<code
className="rounded-sm bg-muted px-1 py-0.5 font-mono text-[0.9em]"
{...props}
/>
),
} satisfies MarkdownComponents;
function MarkdownCode({
code,
incomplete,
language,
}: {
code: string;
incomplete: boolean;
language: string;
}) {
const lines = useHighlightedCode(code, language);
return (
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>{language || "text"}</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton disabled={incomplete} value={code} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>
);
}
export function MarkdownReply({
streaming = false,
text,
}: {
streaming?: boolean;
text: string;
}) {
const document = parseMarkdown(text, {
extensions,
frontmatter: false,
headingIds: false,
});
// An odd number of fences: the last block is still open.
const open = streaming && (text.match(FENCE)?.length ?? 0) % 2 === 1;
return (
<div className="flex min-w-0 flex-col gap-3">
{document.children.map((node, index) => {
const key = `block-${index}`;
if (node.type !== "code") {
return renderBlockReact(node, { components }, key);
}
const incomplete = open && index === document.children.length - 1;
return (
<MarkdownCode
code={incomplete ? node.value.replace(PARTIAL_FENCE, "") : node.value}
incomplete={incomplete}
key={key}
language={node.lang ?? ""}
/>
);
})}
</div>
);
}
frontmatter: falsestops a reply that opens with---from losing its first lines once a second---arrives. TanStack's AI streaming guide recommends it for model output.headingIds: falsekeeps a heading'sidfrom changing on every word while it streams.- The copy button waits. While the last fence has no closing fence, its code is still arriving, so the button is disabled.
PARTIAL_FENCEtrims a closing fence that has half arrived, so one or two stray backticks never show as code. - Inline code gets a chip. A reply in a Message isn't inside Prose, so the
codemapping styles code spans itself. It only reaches inline code here, because the fences never go throughrenderBlockReact. - Only top-level fences become Code Blocks. A fence inside a list item or a quote is rendered by
renderBlockReactas a plain<pre>.
useHighlightedCode returns colored lines on the first render, with nothing to load. On the server, highlightCode from @/lib/highlighter does the same job, as Code Block shows.
Stream a reply
Pass the whole text received so far on every update, not the latest chunk. TanStack Markdown parses the full string again each time, synchronously, so there's no parser state to keep between updates, and its React keys come from each node's place in the tree, so blocks that didn't change keep their DOM.
- Keep one component per reply. Key it by the message or part id, never by its text. A new key remounts the reply: the reader loses their selection, and any block they opened closes.
- Expect the last block to settle. The streaming extension hides an empty trailing heading, quote or list item until its text arrives, and an unclosed fence shows the code received so far. Unclosed
**, backticks and links stay literal text until their closing delimiter arrives, so a bold word shows its asterisks for a moment. - Code costs little.
useHighlightedCodetokenizes the block again on each update, and a line that didn't change keeps the nodes it had. - Batch tiny tokens. If tokens arrive faster than the screen should repaint, update less often. With the AI SDK,
useChat({ throttle: 50 })updates the messages at most every 50 ms.
Five blocks written three characters at a time: a hook, a command, a diff, a route with highlighted lines and an env file. Each copy button stays disabled until its block is complete. It's Code Block streaming on its own, the part of a reply that changes the most.
Put it in a message
In a chat, the reply is the page's text. Render it straight into the Message, as Chat does, or in a ghost Bubble, which has no frame and takes the column's full width. Keep the person's own message as plain text in a Bubble: what they typed is what they see.
import { MarkdownReply } from "@/components/markdown-reply";
import { Bubble, BubbleContent } from "@/components/ui/bubble";
import { Message, MessageContent } from "@/components/ui/message";
export function Turn(props: { question: string; reply: string; streaming: boolean }) {
return (
<>
<Message align="end">
<MessageContent>
<Bubble align="end" variant="muted">
<BubbleContent>{props.question}</BubbleContent>
</Bubble>
</MessageContent>
</Message>
<Message>
<MessageContent>
<MarkdownReply streaming={props.streaming} text={props.reply} />
</MessageContent>
</Message>
</>
);
}A question in a default Bubble on the end side, and the answer in a ghost Bubble, unframed and full width, with bold text and inline code. The demo's answer is a fixed string with a few lines of parsing; in your app it goes through MarkdownReply.
For a full chat on a model, follow AI SDK or TanStack AI: both render text parts with MarkdownReply.
Security
Treat a model's output as untrusted: a prompt can steer what it writes. TanStack Markdown's defaults are safe for it, as long as you keep them.
- Raw HTML is escaped.
<script>in a reply shows as text.allowHtml: trueturns raw HTML on, and the React renderer then injects it withdangerouslySetInnerHTML, so never enable it for content you didn't write. - Executable URLs are removed. Links and images with
javascript:,vbscript:,file:ordata:URLs lose them. Relative URLs, fragments,http:,https:,mailto:andtel:stay. - Highlighted code is React nodes.
useHighlightedCodereturns elements, not an HTML string. If you use TanStack Markdown's ownhighlighteroption instead, its output is inserted as HTML, so use only a highlighter that escapes the code. - Links and images still go where the reply says. A remote image loads as soon as it renders, so a reply can make the reader's browser request any URL it writes. Set your own policy in
components.
const components = {
img({ alt, src }) {
return typeof src === "string" &&
src.startsWith("https://images.example.com/") ? (
<img alt={alt ?? ""} src={src} />
) : (
<span>{alt}</span>
);
},
} satisfies MarkdownComponents;TanStack Markdown isn't an HTML sanitizer. If your threat model needs an independent layer, sanitize the final HTML too.
Other renderers
TanStack Markdown is what our demos use. Two other React renderers are common, and any of them renders into the same components: put the output in Prose, or map its code to a Code Block.
| TanStack Markdown | Streamdown | react-markdown | |
|---|---|---|---|
| Version | @tanstack/markdown 1.0 | streamdown 2.5 | react-markdown 10 |
| Built on | Its own parser, no runtime dependencies | remark and rehype, with rehype-harden | remark and rehype |
| Streaming | streamingMarkdownExtension() | Its purpose: isAnimating while a reply streams | No streaming option |
| Code highlighting | A callback you pass, or Code Block | Shiki, through the @streamdown/code plugin | A rehype plugin you add |
| Setup | None | An @source line in your Tailwind CSS | None |
| Import | import { Markdown } from "@tanstack/markdown/react" | import { Streamdown } from "streamdown" | import Markdown from "react-markdown" |
TanStack Markdown supports a documented subset of Markdown, chosen for docs and blogs: no setext headings (=== underlines), no indented code blocks, and no autolinks, so a bare URL stays text. Streamdown describes itself as a drop-in replacement for react-markdown, built for AI streaming. Read the Streamdown docs (opens in a new tab) before choosing it for a project.
FAQ
Does shadcn.io have a Markdown component?
No. Markdown isn't a file you install: TanStack Markdown (opens in a new tab) parses and renders the string, Prose styles an article, and Code Block takes the fences. The Article and MarkdownReply files on this page are short enough to copy and own.
Which Markdown syntax does TanStack Markdown support?
ATX headings (#), paragraphs, fenced code with a language and metadata, blockquotes, ordered, unordered and task lists, tables with alignment, thematic breaks, footnotes, strikethrough, links, images and reference links. It doesn't support setext headings, indented code blocks or autolink literals, and raw HTML only renders with allowHtml.
Why don't bare URLs in a reply become links?
TanStack Markdown doesn't turn a bare URL into a link: autolink literals are outside its supported syntax, so https://example.com stays text. Write links as [text](https://example.com), or tell the model to in its instructions.
How do I stop a streaming reply from flickering or remounting?
Render one MarkdownReply per reply, keyed by its message or part id, and pass it the full text so far on every update. TanStack Markdown keys its elements by their place in the tree, so blocks that didn't change keep their DOM, and the streaming extension hides empty trailing blocks while they're incomplete. A key built from the text remounts the reply on every token.
Is it safe to render a model's Markdown?
With the defaults, yes: raw HTML is escaped, and javascript:, vbscript:, file: and data: URLs are removed from links and images. Keep allowHtml off, and set a policy for links and remote images in components, since a reply can still point them anywhere. TanStack Markdown isn't a full HTML sanitizer.
How do I add syntax highlighting to fenced code?
Render each fence as a Code Block and color it with useHighlightedCode(code, language), which Code Block's install adds, as MarkdownReply does. It runs on TanStack Highlight, synchronously, so the first render is already colored. Its grammars are listed on the Code Block page; a language it doesn't list renders as plain text.
Can I render Markdown in a Server Component?
Yes. TanStack Markdown's Markdown uses no hooks, so Article renders on the server and the page ships as HTML. MarkdownReply is a Client Component because useHighlightedCode is a hook; on the server, highlightCode from @/lib/highlighter colors code instead.
How do I style the rendered Markdown?
Wrap it in Prose and every element takes the article styles, with nothing to add per element. For one element styled differently, map its tag to your own component in components, as MarkdownReply does for inline code.
Should the person's own messages render as Markdown?
Usually not. Show what they typed as plain text in a Bubble, so a stray * or # reads as they wrote it. Markdown is for the model's reply, which is written to be rendered.
How do I add anchor links to headings in a README?
Heading ids are on by default, unique on the page. Add headingAnchors to Markdown for a # link inside each heading, hidden from screen readers and out of the tab order. Pass an object instead of true to set its content and class.
What happens to front matter?
A leading --- block is taken out and not rendered. Its raw text is on the parsed document's frontmatter, unparsed, for your own YAML parser. Turn it off with frontmatter: false, which MarkdownReply does so a reply can't lose its opening lines.
Can I use Streamdown or react-markdown instead?
Yes. Both render into the same components: wrap the output in Prose and map code to a Code Block. Streamdown is built for streaming and brings Shiki highlighting through a plugin, but needs an @source line in your Tailwind CSS. react-markdown runs the remark and rehype pipeline and takes their plugins.