React Markdown Renderer with Streaming and Components

Render Markdown in React and Next.js with custom components, plugins, React Server Components, and streaming for AI chat output.

@comark/react renders Markdown and Comark components in React and Next.js, with plugin support, Server Components, and streaming.

Installation

pnpm add @comark/react

<Markdown>

<Markdown> parses and renders Markdown in one component.

<Markdown> is an async component. You can also use the <MarkdownDocument> component to handle parsing yourself.
App.tsx
import { Markdown } from '@comark/react'

const content = `# Hello World

This is **markdown** with Comark components.
`

export default function App() {
  return <Markdown>{content}</Markdown>
}

Usage

Pass Markdown content via children or the value prop. value accepts a Markdown string or a pre-parsed MarkdownDocument:

<Markdown>{content}</Markdown>
Passing a document to <Markdown> skips parsing at runtime, but the parser is still bundled because Markdown imports it. To keep the client bundle free of the parser, use <MarkdownDocument> instead.

Props

PropTypeDefaultDescription
childrenReact.ReactNode-Markdown content to parse and render
valuestring | MarkdownDocument''Markdown string or pre-parsed document (alternative to children)
optionsParserOptions{}Parser options (autoUnwrap, autoClose, and others)
pluginsComarkPlugin[][]Array of plugins
unwrapboolean | string | string[]falseStrip wrapper tags (MDC unwrap). true unwraps <p>; a comma- or space-separated string or array peels tags sequentially, for example "ul li"
componentsRecord<string, ComponentType>{}Custom React component mappings
componentsManifest(name: string) => Promise<Component>undefinedDynamic component resolver
streamingbooleanfalseEnable streaming mode
effectsreadonly StreamEffect[]undefinedStream effects from comark/stream, such as caret(), fade() and pace()
dataRecord<string, unknown>undefinedRuntime values referenced from Markdown via :prop="data.path"
transformNodeNodeTransform | NodeTransform[]undefinedChange the tag or props of element nodes right before they render
classNamestringundefinedCSS class for wrapper element
...attributesHTMLAttributes<HTMLDivElement>-Any other HTML attribute (id, style, role, data-*, aria-*, ...) is set on the wrapper <div>

options

See ParserOptions for available options.

App.tsx
<Markdown options={{ autoUnwrap: true, autoClose: true }}>
  {content}
</Markdown>

plugins

See ComarkPlugin for available plugins.

App.tsx
import { Markdown } from '@comark/react'
import shiki from '@comark/react/plugins/shiki'
import githubLight from '@shikijs/themes/github-light'
import githubDark from '@shikijs/themes/github-dark'

const plugins = [
  shiki({
    themes: { light: githubLight, dark: githubDark }
  })
]

export default function App() {
  return <Markdown plugins={plugins}>{content}</Markdown>
}

For the math and mermaid plugins, also pass the companion components:

App.tsx
import { Markdown } from '@comark/react'
import math, { Math } from '@comark/react/plugins/math'
import mermaid, { Mermaid } from '@comark/react/plugins/mermaid'
import 'katex/dist/katex.min.css'

export default function App() {
  return (
    <Markdown
      value={markdown}
      components={{ Math, Mermaid }}
      plugins={[math(), mermaid()]}
    />
  )
}

components

Map custom React components to Comark elements in your Markdown.

Create a component

components/Alert.tsx
interface AlertProps {
  type?: 'info' | 'warning' | 'error' | 'success'
  children: React.ReactNode
}

export default function Alert({ type = 'info', children }: AlertProps) {
  return (
    <div className={`alert alert-${type}`} role="alert">
      {children}
    </div>
  )
}

Map the tag to your component

App.tsx
import { Markdown } from '@comark/react'
import Alert from './components/Alert'
import Card from './components/Card'

const components = { alert: Alert, card: Card }

export default function App() {
  return <Markdown components={components}>{content}</Markdown>
}

Use it in your Markdown

::alert{type="warning"}
This is a warning message!
::
See Component bindings for how props and slots map to your React component, or Component syntax for nested components, inline syntax, and attributes.

componentsManifest

Pass a function to load components on demand. Comark resolves each component with React.lazy() and wraps it in <Suspense>, in both <Markdown> and <MarkdownDocument>:

App.tsx
import { Markdown } from '@comark/react'

const manifest = (name: string) => {
  return import(`./components/prose/${name}.tsx`)
}

export default function App() {
  return <Markdown componentsManifest={manifest}>{content}</Markdown>
}

data

Expose runtime values to Markdown authors. Any prop written with a : prefix resolves against the render context { frontmatter, meta, data, props } when its value isn't valid JSON. See Data binding for details.

App.tsx
import { Markdown } from '@comark/react'

const user = { name: 'Ada', role: 'admin' }
const content = `Hello, :badge{:label="data.user.name"}!`

export default function App() {
  return <Markdown value={content} data={{ user }} />
}

transformNode

Change an element's tag or props right before it renders, using values that are only known at render time. The function receives the node's tag, its resolved props, and the render context. It returns a new tag, new props, or nothing to keep the node as it is. See Transforming nodes before render for the full rules.

App.tsx
import { Markdown } from '@comark/react'
import type { NodeTransform } from '@comark/react'

const user = { id: 42 }
const content = `::cta\nOpen your dashboard\n::`

const transformNode: NodeTransform = ({ tag, props }) => {
  if (tag !== 'cta') return
  return { tag: 'a', props: { ...props, href: `/users/${user.id}/dashboard` } }
}

export default function App() {
  return <Markdown value={content} transformNode={transformNode} />
}

Comark renders what the function returns as-is, without sanitizing it, and the security plugin doesn't apply to it. Validate anything you build from untrusted data, such as URLs from data.

Define the function outside the component, or memoize it. A new array on every render makes the document render again. With streaming, <Markdown> renders through the client-only MarkdownClient, so a Server Component can't pass it a function. Pass transformNode from a Client Component instead.

defineMarkdownComponent

Creates a pre-configured <Markdown> component with default options, plugins, and components.

Usage

Expose your configured component

markdown.ts
import { defineMarkdownComponent } from '@comark/react'
import shiki from '@comark/react/plugins/shiki'
import math, { Math } from '@comark/react/plugins/math'
import mermaid, { Mermaid } from '@comark/react/plugins/mermaid'
import githubLight from '@shikijs/themes/github-light'
import githubDark from '@shikijs/themes/github-dark'
import CustomAlert from './components/CustomAlert'

export const AppMarkdown = defineMarkdownComponent({
  name: 'AppMarkdown',

  plugins: [
    math(),
    mermaid(),
    shiki({
      themes: {
        light: githubLight,
        dark: githubDark
      },
    }),
  ],

  components: {
    Math,
    Mermaid,
    alert: CustomAlert,
  },
})

Use it in your templates

App.tsx
import { AppMarkdown } from './markdown'

export default function App() {
  return (
    <>
      <AppMarkdown>{content}</AppMarkdown>

      <AppMarkdown components={{ alert: DifferentAlert }}>
        {content}
      </AppMarkdown>
    </>
  )
}

Options

OptionTypeDefaultDescription
extendsReturnType<typeof defineMarkdownComponent>undefinedInherit plugins and components from another component
namestringundefinedComponent name for debugging
autoUnwrapbooleantrueUnwrap single paragraph elements inside components
autoClosebooleantrueAuto-close incomplete Markdown syntax
linkifybooleantrueDeprecated. Use registerDefaultPlugins: false and register linkify() instead
registerDefaultPluginsbooleantrueRegister default plugins (linkify, frontmatter, html, alert, task-list, components, attributes)
pluginsComarkPlugin[][]Array of plugins
componentsRecord<string, ComponentType>{}Custom React component mappings
transformNodeNodeTransform | NodeTransform[]undefinedNode transforms that run before the instance's own transformNode
classNamestringundefinedAdditional CSS classes for the wrapper div

extends

Inherit plugins and components from another component, then layer your own on top:

markdown/index.ts
import { defineMarkdownComponent } from '@comark/react'
import shiki from '@comark/react/plugins/shiki'
import githubLight from '@shikijs/themes/github-light'
import githubDark from '@shikijs/themes/github-dark'
import toc from '@comark/react/plugins/toc'
import math, { Math } from '@comark/react/plugins/math'
import CodeBlock from './components/CodeBlock'

const BaseMarkdown = defineMarkdownComponent({
  name: 'BaseMarkdown',
  plugins: [shiki({ themes: { light: githubLight, dark: githubDark } })],
  components: { pre: CodeBlock },
})

export const ArticleMarkdown = defineMarkdownComponent({
  name: 'ArticleMarkdown',
  extends: BaseMarkdown,
  plugins: [toc({ depth: 3 }), math()],
  components: { Math },
})

export const CommentMarkdown = defineMarkdownComponent({
  name: 'CommentMarkdown',
  extends: BaseMarkdown,
})

Merging behavior

  • plugins: Arrays are concatenated (config plugins + prop plugins)
  • components: Props override config (prop components take precedence)
  • Other options: Props override config

Usage with Next.js App Router

markdown.ts
'use client'

import { defineMarkdownComponent } from '@comark/react'
import math, { Math } from '@comark/react/plugins/math'

export const DocsMarkdown = defineMarkdownComponent({
  name: 'DocsMarkdown',
  plugins: [math()],
  components: { Math },
})
app/docs/[slug]/page.tsx
import { DocsMarkdown } from '@/components/markdown'

export default async function Page({ params }: { params: { slug: string } }) {
  const content = await getDocContent(params.slug)
  return <DocsMarkdown>{content}</DocsMarkdown>
}

<MarkdownDocument>

Renders a pre-parsed MarkdownDocument without any parsing. Use it when you parse on the server, in a build step, or via an API, so no parser or plugin code is shipped to the browser.

Parsing

Parse your Markdown content and pass the document directly in a React Server Component:

app/docs/[slug]/page.tsx
import { createMarkdownParser } from 'comark'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { MarkdownDocument } from '@comark/react'
import Alert from '@/components/Alert'

const parse = createMarkdownParser()

export default async function DocsPage({ params }: { params: { slug: string } }) {
  const markdown = await readFile(join('content', `${params.slug}.md`), 'utf-8')
  const document = await parseMarkdown(markdown)

  return <MarkdownDocument value={document} components={{ alert: Alert }} />
}

Renderer props

PropTypeDefaultDescription
valueMarkdownDocument-Required. The parsed document returned by parseMarkdown()
componentsRecord<string, ComponentType>{}Custom React component mappings
componentsManifestComponentManifestundefinedDynamic component resolver for lazy-loaded components
streamingbooleanfalseEnable streaming mode
effectsreadonly StreamEffect[]undefinedStream effects from comark/stream, such as caret(), fade() and pace()
dataRecord<string, unknown>undefinedRuntime values referenced from Markdown via :prop="data.path"
transformNodeNodeTransform | NodeTransform[]undefinedChange the tag or props of element nodes right before they render
classNamestringundefinedCSS class for the wrapper <div>
...attributesHTMLAttributes<HTMLDivElement>-Any other HTML attribute (id, style, role, data-*, aria-*, ...) is set on the wrapper <div>

defineMarkdownDocumentComponent

Creates a pre-configured <MarkdownDocument> component with default component mappings.

Setup

Expose your configured renderer

markdown/index.ts
import { defineMarkdownDocumentComponent } from '@comark/react'
import Alert from './components/Alert'
import CodeBlock from './components/CodeBlock'

export const ArticleMarkdownDocument = defineMarkdownDocumentComponent({
  name: 'ArticleMarkdownDocument',
  components: {
    alert: Alert,
    pre: CodeBlock,
  },
})

Page integration

app/docs/[slug]/page.tsx
import { parseMarkdown } from 'comark'
import { ArticleMarkdownDocument } from '@/markdown'

export default async function Page({ params }: { params: { slug: string } }) {
  const markdown = await getContent(params.slug)
  const document = await parseMarkdown(markdown)

  return <ArticleMarkdownDocument value={document} />
}

Renderer options

OptionTypeDefaultDescription
extendsReturnType<typeof defineMarkdownDocumentComponent>undefinedInherit component mappings from another renderer
namestringundefinedComponent name for debugging
componentsRecord<string, ComponentType>{}Custom React component mappings
transformNodeNodeTransform | NodeTransform[]undefinedNode transforms that run before the instance's own transformNode
classNamestringundefinedAdditional CSS classes for the wrapper div

Inheritance

Inherit component mappings from another renderer, then layer your own on top:

markdown/index.ts
import { defineMarkdownDocumentComponent } from '@comark/react'
import CodeBlock from './components/CodeBlock'
import ProseA from './components/ProseA'
import Alert from './components/Alert'
import CommentAlert from './components/CommentAlert'

const BaseMarkdownDocument = defineMarkdownDocumentComponent({
  name: 'BaseMarkdownDocument',
  components: { pre: CodeBlock, a: ProseA },
})

export const ArticleMarkdownDocument = defineMarkdownDocumentComponent({
  name: 'ArticleMarkdownDocument',
  extends: BaseMarkdownDocument,
  components: { alert: Alert },
})

export const CommentMarkdownDocument = defineMarkdownDocumentComponent({
  name: 'CommentMarkdownDocument',
  extends: BaseMarkdownDocument,
  components: { alert: CommentAlert },
})

Live documents

MarkdownLive is a client wrapper around MarkdownDocument that subscribes to an ambient context so external sources can update a mounted renderer, such as HMR, a collaboration socket, an agent, or devtools. It accepts the same props as MarkdownDocument plus documentKey. The listen key comes from meta.key (set by a plugin) or the documentKey prop. When globalThis.comarkContext exists, the renderer listens for updates on that key, re-renders on change, and unsubscribes on unmount. MarkdownDocument stays free of client-only hooks so it can render in a React Server Component. Without a context, the key is ignored.

import { MarkdownLive } from '@comark/react'

<MarkdownLive documentKey="page" value={document} />

A driver installs the context once and pushes updates by key with set() to replace the whole document, or patch() to edit individual nodes with structural sharing so only the changed branch re-renders:

import { createComarkContext, parseMarkdown } from 'comark'

const ctx = createComarkContext() // installs globalThis.comarkContext
const doc = ctx.get('page', await parseMarkdown('# Hello')) // seed on first access

doc.set(await parseMarkdown('# Replaced'))
doc.patch({ op: 'insert', path: [1], node: ['p', {}, 'inserted'] })

A path indexes into document.nodes, where the first segment selects a top-level node and each later segment selects a child of that element. Patch operations include replace, insert, and remove (each taking a path), along with meta, frontmatter, and data merges. @comark/vue, @comark/svelte, and @comark/angular share the same context API.


Component bindings

Comark maps component attributes and slots in Markdown to React props.

Prop binding

Attributes in Comark syntax pass as props to your component. Use the : prefix to pass typed values. Comark converts HTML attribute names to their React equivalents:

MarkdownReact prop
{type="warning"}type="warning" (string)
{:count="5"}count={5} (number)
{:active="true"}active={true} (boolean)
{:config='{"key":"val"}'}config={{ key: 'val' }} (object)
{class="highlight"}className="highlight"
{tabindex="0"}tabIndex={0}
{style="color: red"}style={{ color: 'red' }}

Named slots

Named slots in Comark (#slotname) map to slot{Name} props in React:

  • Default slot → children
  • Named slots → slot{Name} (for example, #footer → slotFooter)
interface CardProps {
  title?: string
  children?: React.ReactNode
  slotFooter?: React.ReactNode
}

export default function Card({ title, children, slotFooter }: CardProps) {
  return (
    <div className="card">
      {title && <h3>{title}</h3>}
      <div className="card-body">{children}</div>
      {slotFooter && <div className="card-footer">{slotFooter}</div>}
    </div>
  )
}

Overriding HTML elements

Override how native HTML elements render by mapping a component to their tag name via the components prop.

Create overridden version

components/Heading.tsx
interface HeadingProps {
  __node?: ElementNode
  id?: string
  children: React.ReactNode
}

export default function Heading({ __node, id, children }: HeadingProps) {
  const Tag = __node?.[0] || 'h2'
  return (
    <Tag id={id} className="heading">
      {id && <a href={`#${id}`} className="anchor">#</a>}
      {children}
    </Tag>
  )
}

Map

App.tsx
<Markdown components={{ h1: Heading, h2: Heading, h3: Heading }}>
  {content}
</Markdown>

Resolution order

Components are resolved in this order:

  1. Prose{PascalTag}: for example, ProseH1 for h1
  2. {PascalTag}: for example, Alert for alert
  3. {tag}: for example, alert

If no custom component matches, the tag renders as a native HTML element.


Streaming

Render Markdown incrementally as chunks arrive from an AI stream or live preview.

Setup

The client reuses completed blocks as text is appended. Keep options and plugins references stable between updates. Changing either, or unwrap, creates a new parser.

Set streaming to true while content is being received, then false when done. The final update parses the complete document:

components/AiChat.tsx
import { useState } from 'react'
import { Markdown } from '@comark/react'
import { caret } from 'comark/stream'

const effects = [caret()]

export default function AiChat() {
  const [content, setContent] = useState('')
  const [isStreaming, setIsStreaming] = useState(false)

  async function askAI(prompt: string) {
    setContent('')
    setIsStreaming(true)

    const response = await fetch('/api/chat', {
      method: 'POST',
      body: JSON.stringify({ prompt }),
    })

    const reader = response.body!.getReader()
    const decoder = new TextDecoder()
    let accumulated = ''

    while (true) {
      const { done, value } = await reader.read()
      if (done) break
      accumulated += decoder.decode(value, { stream: true })
      setContent(accumulated)
    }

    setIsStreaming(false)
  }

  return (
    <Markdown streaming={isStreaming} effects={effects}>
      {content}
    </Markdown>
  )
}
autoClose is enabled by default and closes incomplete syntax such as **bold text on every parse. Disable it with options={{ autoClose: false }}.

Stream effects

Pass effects from comark/stream through the effects prop. Effects run in array order, so put pace() first, then fade(), then caret(). Define the array once, outside the component, so effects keep their state between renders.

App.tsx
import { caret, fade } from 'comark/stream'

const effects = [fade(), caret()]

<Markdown streaming={isStreaming} effects={effects}>{content}</Markdown>

See Stream effects for every option and for writing custom effects.

Caret

caret() appends a blinking cursor to the last text node while streaming is true. Import it from comark/stream and pass it through effects:

The caret and fade props were removed. For example, caret becomes effects={[caret()]} and fade={{ delay: 30 }} becomes effects={[fade({ delay: 30 })]}, with both imported from comark/stream.
App.tsx
import { caret } from 'comark/stream'

// Pass a custom class to style the caret yourself
const effects = [caret({ class: 'my-caret' })]

<Markdown streaming={isStreaming} effects={effects}>{content}</Markdown>
.my-caret {
  display: inline-block;
  width: 2px;
  height: 1em;
  background: currentColor;
  animation: blink 1s step-end infinite;
  vertical-align: text-bottom;
}

@keyframes blink {
  50% { opacity: 0; }
}

Fade-in

fade() fades in new text as it streams. Import it from comark/stream and pass it through effects. Only characters that were not on screen yet fade, and code blocks, math, and diagrams appear without animation:

App.tsx
import { fade } from 'comark/stream'

// Stagger words, slower animation
const effects = [fade({ delay: 30, duration: 400 })]

<Markdown streaming={isStreaming} effects={effects}>{content}</Markdown>

Pass class to animate with your own CSS. See Stream effects for every option and for writing custom effects.


TypeScript support

Use ComarkPlugin from comark to type plugin arrays, and ElementNode to type the __node prop in components that override HTML elements:

ComarkWrapper.tsx
import type { ComponentType } from 'react'
import type { ComarkPlugin } from 'comark'
import { Markdown } from '@comark/react'

interface Props {
  content: string
  components?: Record<string, ComponentType<any>>
  plugins?: ComarkPlugin[]
}

export default function ComarkWrapper({ content, components, plugins }: Props) {
  return <Markdown components={components} plugins={plugins}>{content}</Markdown>
}
components/Heading.tsx
import type { ElementNode } from 'comark'

interface HeadingProps {
  __node?: ElementNode
  id?: string
  children: React.ReactNode
}

export default function Heading({ __node, id, children }: HeadingProps) {
  const Tag = __node?.[0] || 'h2'
  return <Tag id={id}>{children}</Tag>
}

© 2026 Vercel, Inc.