Skip to content

MDX

Write Markdown pages that compile to Xote views and embed Xote components.

docs/advanced/mdx-support.md
moduleXote.Mdxboundarysrc/Mdx.resientryxote/mdxversion7.2.0
Raw Markdown

MDX lets Markdown files compile to Xote views. Use it when docs, articles or other long-form pages should live as .mdx files but still embed Xote components. This docs site is built that way.

Status: The MDX runtime is deliberately small. It provides the JSX runtime bridge and helpers for component overrides; your bundler still compiles the MDX.

Install the MDX plugin

Add the MDX Rollup plugin to the Vite app that imports .mdx files.

1npm install --save-dev @mdx-js/rollup

For GitHub Flavored Markdown features such as tables, add remark-gfm too.

1npm install --save-dev remark-gfm

Configure Vite

Point MDX at Xote's automatic JSX runtime.

1// vite.config.js
2import mdx from "@mdx-js/rollup"
3import remarkGfm from "remark-gfm"
4import { defineConfig } from "vite"
5
6export default defineConfig({
7 plugins: [
8 mdx({
9 jsxImportSource: "xote",
10 jsxRuntime: "automatic",
11 remarkPlugins: [remarkGfm],
12 }),
13 ],
14})

With jsxImportSource set to "xote", MDX uses the runtime exported from xote/jsx-runtime and xote/jsx-dev-runtime.

Import MDX from ReScript

Bind the compiled MDX module as an Mdx.document, then render it to a View.node.

1// ArticlePage.res
2@module("./article.mdx") external article: Mdx.document = "default"
3
4let app = () => {
5 <main class="article-shell">
6 {Mdx.render(article, ())}
7 </main>
8}
9
10View.mountById(app(), "root")

Override elements with components

Mdx.render takes an optional components dictionary. Keys are Markdown/HTML element names or the names of custom components used in the MDX; values are Xote components wrapped with Mdx.component.

1// ArticlePage.res
2type mdxProps = {
3 children?: Mdx.children,
4 href?: string,
5}
6
7module Link = {
8 let make = (props: mdxProps) => {
9 <a href={props.href->Option.getOr("#")} target="_blank" attrs=[View.attr("rel", "noreferrer")]>
10 {View.fragment(
11 switch props.children {
12 | Some(children) => Mdx.childrenToNodes(children)
13 | None => []
14 },
15 )}
16 </a>
17 }
18}
19
20let components = Mdx.components([
21 ("a", Mdx.component(Link.make)),
22])
23
24let page = Mdx.render(article, ~components, ())

Render children

MDX children arrive as JavaScript values, because the MDX compiler decides their shape. Turn them back into Xote values with the Mdx helpers:

  • Mdx.childrenToNodes(children) returns an array of View.node.
  • Mdx.childrenToText(children) extracts plain text, for things like syntax highlighting or heading ids.
1// ArticleHeading.res
2type headingProps = {children?: Mdx.children}
3
4module Heading = {
5 let make = (props: headingProps) => {
6 <h2 class="article-heading">
7 {View.fragment(
8 switch props.children {
9 | Some(children) => Mdx.childrenToNodes(children)
10 | None => []
11 },
12 )}
13 </h2>
14 }
15}

Write MDX with Xote components

An MDX file can mix Markdown, HTML-like tags, and named components supplied through the components dictionary.

1{/* article.mdx */}
2
3# MDX with Xote
4
5This paragraph renders as Xote nodes.
6
7<Example />
8
9<a href="https://mdxjs.com">MDX link rendered through a Xote component override</a>

Override Markdown output by key:

1// ArticlePage.res
2let components = Mdx.components([
3 ("h1", Mdx.component(ArticleTitle.make)),
4 ("p", Mdx.component(LeadParagraph.make)),
5 ("Example", Mdx.component(Example.make)),
6])

Tables and other GitHub Markdown

Enable remark-gfm when your content uses GFM syntax such as tables.

1{/* article.mdx */}
2
3| Feature | Supported |
4| --- | --- |
5| Component overrides | Yes |
6| Markdown tables | Yes, with `remark-gfm` |

Without remark-gfm, the base MDX parser reads pipe tables as plain paragraphs.

What the runtime handles

Xote's MDX runtime turns MDX's automatic JSX calls into View.node values. It supports:

  • HTML and SVG tags
  • event props such as onClick
  • static, signal, computed, and MaybeSignal-wrapped attributes
  • fragments and nested children
  • reserved key handling for keyed reconciliation
  • MDX internal props such as mdxType and originalType

Everything else stays in the bundler: MDX parsing, remark and rehype plugins, syntax extensions and file loading. Configure those in Vite, or whatever build pipeline imports your .mdx files.

Tips

  • Keep MDX content about prose and examples; put stateful UI in named Xote components.
  • Use overrides for links, code blocks, headings and demo panels, so MDX pages match the rest of your app.
  • Type only the props each override needs, then wrap the component with Mdx.component.
  • Add remark-gfm when your content uses tables, task lists, autolinks or strikethrough.
  • MDX pages can be server-rendered and hydrated like any other view; see Server rendering.

Summary

.mdx files compile, through your bundler's MDX plugin, to components that call Xote's automatic JSX runtime (xote/jsx-runtime), so a compiled MDX document returns a View.node. The Mdx module is the typed boundary from ReScript: bind the document as Mdx.document, render it with Mdx.render, and replace elements or provide custom components with Mdx.components + Mdx.component. Xote does not compile MDX itself. The rule that matters most: override props arrive as an untyped JavaScript object, so the ReScript props record MUST use the exact JavaScript prop names MDX passes (className, href, children, …).

Availability

ItemValue
ModulesMdx; the JSX runtime xote/jsx-runtime and xote/jsx-dev-runtime
Import / entryxote/mdx (or xote with -open Xote); the bundler resolves xote/jsx-runtime from jsxImportSource: "xote"
First stable version7.0.0
Statusstable since 7.1.0
PPX requiredNo. Components used in MDX may use @xote.component or not
Bundler requirement@mdx-js/rollup 3.x (Vite/Rollup); remark-gfm for tables; rehype-slug if headings need ids

Rules

  1. Configure the MDX plugin with jsxImportSource: "xote" and jsxRuntime: "automatic". MDX then imports jsx, jsxs and Fragment from xote/jsx-runtime (development builds use xote/jsx-dev-runtime, which delegates to the same jsx).
  2. A compiled .mdx file's default export has type Mdx.document = Mdx.props => View.node. Bind it with @module("./file.mdx") external doc: Mdx.document = "default".
  3. Mdx.render(document, ~components=?, ()) calls the document with {components} (or {}) and returns its node. It renders once; MDX content is static.
  4. Mdx.components(entries) builds a dict from (name, component) pairs. Keys are element names MDX emits for Markdown syntax ("h1", "p", "a", "code", "pre", "table", …) or names of custom components used in the MDX ("Counter"). Elements without an entry render as plain HTML elements. Literal lowercase JSX tags in the MDX are never replaced.
  5. Mdx.component(make) casts a typed function 'props => View.node to Obj.t => View.node. No validation happens: the props record's field names MUST match what MDX passes, and every field SHOULD be optional.
  6. For Markdown elements MDX passes the element's attributes as props using JavaScript names: className (not class; e.g. "language-js" on a fenced code block's code), href, title, src, alt, id, plus children.
  7. children is untyped (Mdx.children = Obj.t): a string, a Xote node, an array of those, or absent. Convert it with Mdx.childrenToNodes (to array<View.node>) or Mdx.childrenToText (to string). Never pattern-match on it directly.
  8. Mdx.childrenToNodes: null/undefined/booleans → nothing, arrays are flattened, Xote nodes pass through, anything else becomes a text node via String(value).
  9. Mdx.childrenToText: concatenates strings and the text of View.text nodes and fragments; other nodes (elements, reactive text) contribute "".
  10. For plain elements (no override), the JSX runtime converts props: className → class, htmlFor → for, ariaLabel/dataFoo-style camelCase aria*/data* → kebab-case, a style object → a key:value;… string (camelCase keys to kebab-case, no units added), functions named on[A-Z]… → event listeners, null/undefined props → omitted, a function prop value on a non-event attribute → a reactive attribute, a signal → a reactive attribute.
  11. A function component (an override or a custom component) is wrapped in a lazy component node: it runs when the node renders, under the current owner, and may create signals, effects and resources like any Xote component.
  12. A custom component used in the MDX but missing from components (and not imported in the MDX) makes rendering throw MDX's error: Expected component `Name` to be defined: you likely forgot to import, pass, or provide it.
  13. MDX can import ESM modules, including compiled ReScript output, e.g. import { make as Changelog } from "./Changelog.res.mjs".

API

NameSignatureBehaviour
Mdx.childrenObj.tOpaque children from the MDX runtime.
Mdx.components (type)dict<Obj.t => View.node>Override map.
Mdx.props{components?: components}Props every document accepts.
Mdx.documentprops => View.nodeA compiled .mdx default export.
Mdx.component('props => View.node) => Obj.t => View.nodeMake a typed component usable as an override.
Mdx.components (function)array<(string, Obj.t => View.node)> => componentsBuild the override map.
Mdx.render(document, ~components: components=?, unit) => View.nodeRender a document.
Mdx.childrenToNodeschildren => array<View.node>Children as nodes.
Mdx.childrenToTextchildren => stringChildren as plain text.

Patterns

Use to set up Vite for MDX:

1// vite.config.js
2import mdx from "@mdx-js/rollup"
3import remarkGfm from "remark-gfm"
4import rehypeSlug from "rehype-slug"
5import { defineConfig } from "vite"
6
7export default defineConfig({
8 plugins: [
9 mdx({
10 jsxImportSource: "xote",
11 jsxRuntime: "automatic",
12 remarkPlugins: [remarkGfm],
13 rehypePlugins: [rehypeSlug],
14 }),
15 ],
16})

Use to render a document with overrides: internal links through the router, external links in a new tab, a code block override that reads the language, and a custom interactive component.

1@module("./article.mdx") external article: Mdx.document = "default"
2
3type linkProps = {href?: string, children?: Mdx.children}
4type codeProps = {className?: string, children?: Mdx.children}
5
6module Link = {
7 let make = (props: linkProps) => {
8 let href = props.href->Option.getOr("#")
9 let children = switch props.children {
10 | Some(children) => Mdx.childrenToNodes(children)
11 | None => []
12 }
13 String.startsWith(href, "/")
14 ? Router.link(~to=href, ~children, ())
15 : <a href target="_blank" attrs=[("rel", "noreferrer")]> {View.fragment(children)} </a>
16 }
17}
18
19module Code = {
20 let make = (props: codeProps) => {
21 let source = props.children->Option.mapOr("", Mdx.childrenToText)
22 let language = props.className->Option.getOr("")
23 <code class={language}> {View.text(source)} </code>
24 }
25}
26
27module Counter = {
28 @xote.component
29 let make = () => {
30 let count = Signal.make(0)
31 <button onClick={_ => Signal.update(count, n => n + 1)}> {"Clicked "} {Signal.get(count)} </button>
32 }
33}
34
35let components = Mdx.components([
36 ("a", Mdx.component(Link.make)),
37 ("code", Mdx.component(Code.make)),
38 ("Counter", Mdx.component(Counter.make)),
39])
40
41let page = () => <main> {Mdx.render(article, ~components, ())} </main>

In article.mdx, <Counter /> then renders the interactive component; the code fence's code element gets className: "language-js" and its source as a string child (with a trailing newline).

Anti-patterns

Naming the props field class.

1type codeProps = {class?: string, children?: Mdx.children} // MDX never passes `class`

Symptom: compiles, but the field is always None, so the language class of a code block is lost. Correct: className?: string. Why: rule 6, MDX passes JavaScript prop names.

Using children as a node or string directly.

1let make = (props: {children?: Mdx.children}) => <h2> {Obj.magic(props.children)} </h2>

Symptom: works for single strings, then renders [object Object] or drops content for nested Markdown (emphasis, links, arrays). Correct: View.fragment(props.children->Option.mapOr([], Mdx.childrenToNodes)). Why: rule 7.

Using a custom component without registering it.

1<Counter />

with Mdx.render(article, ()). Symptom: rendering throws Expected component `Counter` to be defined…. Correct: pass ("Counter", Mdx.component(Counter.make)) in components, or import it in the MDX file. Why: rule 12.

Expecting MDX expressions to be reactive.

1Count: {count}

Symptom: renders once, never updates (and count is not in scope unless exported or imported). Correct: put reactive output in a Xote component and use that component in the MDX. Why: rule 3, MDX content renders once.

A style object with unitless lengths.

1<div style={{marginTop: 4}}>…</div>

Symptom: renders style="margin-top:4", which browsers ignore. Correct: style={{marginTop: "4px"}} or a string style="margin-top: 4px". Why: rule 10, no units are added.

Edge cases

  • Indentation inside JavaScript expressions: MDX 3 removes up to two leading spaces from every line of an expression (including template literals passed as props). A multi-line code string passed as code={…} loses two spaces of indentation per line unless you compensate (this docs site adds them back with a Vite transform before MDX runs).
  • rehype-slug ids follow GitHub's slug rules; heading text with backticks or punctuation produces ids without them. Link targets MUST use the generated id.
  • A ref prop must be a View.Ref.t or a function; any other value (a React-style {current} object) is ignored with a console warning.
  • A key prop on an element produces a keyed node (View.Keyed).
  • An override for pre receives the already-built code node as children (a Xote node), not text; override code to get the source text.
  • components replaces elements MDX creates from Markdown syntax (a paragraph becomes p, a link a, …) and capitalized component names. Lowercase tags written literally as JSX in the MDX (<div>…</div>) are not replaced: they render through the JSX runtime as plain elements even when components has a div entry.

SSR and hydration

  • A rendered MDX document is an ordinary node tree: SSR.renderToString renders it on the server and Hydration.hydrateById adopts it on the client, as long as both sides render the same document with the same components.
  • Overrides and custom components follow normal server rules: View.onMount for browser-only code; effects run on the server too (see /docs/advanced/ssr).
  • MDX is compiled at build time by the bundler; the server bundle (for example vite build --ssr) needs the same MDX plugin configuration as the client bundle.

Verify

  • Build errors: Cannot find module './article.mdx' means the MDX plugin is missing from the bundler config; a JSX runtime import error for react/jsx-runtime means jsxImportSource: "xote" is missing.
  • Server test: SSR.renderToString(() => Mdx.render(article, ~components, ())) and assert the expected HTML (overridden elements show your classes; className became class).
  • Override props test: temporarily log Object.keys(props) in an override to see exactly which props MDX passes for that element.
  • A missing component is a runtime error at render, not a compile error; render every MDX page in a test to catch it.
  • /docs/learn/components — writing the components used as overrides.
  • /docs/learn/routing — Router.link for internal links in overrides.
  • /docs/advanced/ssr — rendering MDX pages on the server.
  • /docs/api/view — View.node, View.fragment, View.text.