MDX
Write Markdown pages that compile to Xote views and embed Xote components.
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.js2import mdx from "@mdx-js/rollup"3import remarkGfm from "remark-gfm"4import { defineConfig } from "vite"56export 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.res2@module("./article.mdx") external article: Mdx.document = "default"34let app = () => {5 <main class="article-shell">6 {Mdx.render(article, ())}7 </main>8}910View.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.res2type mdxProps = {3 children?: Mdx.children,4 href?: string,5}67module 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}1920let components = Mdx.components([21 ("a", Mdx.component(Link.make)),22])2324let 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 ofView.node.Mdx.childrenToText(children)extracts plain text, for things like syntax highlighting or heading ids.
1// ArticleHeading.res2type headingProps = {children?: Mdx.children}34module 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 */}23# MDX with Xote45This paragraph renders as Xote nodes.67<Example />89<a href="https://mdxjs.com">MDX link rendered through a Xote component override</a>
Override Markdown output by key:
1// ArticlePage.res2let 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 */}23| 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
keyhandling for keyed reconciliation - MDX internal props such as
mdxTypeandoriginalType
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-gfmwhen 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
| Item | Value |
|---|---|
| Modules | Mdx; the JSX runtime xote/jsx-runtime and xote/jsx-dev-runtime |
| Import / entry | xote/mdx (or xote with -open Xote); the bundler resolves xote/jsx-runtime from jsxImportSource: "xote" |
| First stable version | 7.0.0 |
| Status | stable since 7.1.0 |
| PPX required | No. 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
- Configure the MDX plugin with
jsxImportSource: "xote"andjsxRuntime: "automatic". MDX then importsjsx,jsxsandFragmentfromxote/jsx-runtime(development builds usexote/jsx-dev-runtime, which delegates to the samejsx). - A compiled
.mdxfile's default export has typeMdx.document = Mdx.props => View.node. Bind it with@module("./file.mdx") external doc: Mdx.document = "default". Mdx.render(document, ~components=?, ())calls the document with{components}(or{}) and returns its node. It renders once; MDX content is static.Mdx.components(entries)builds adictfrom(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.Mdx.component(make)casts a typed function'props => View.nodetoObj.t => View.node. No validation happens: the props record's field names MUST match what MDX passes, and every field SHOULD be optional.- For Markdown elements MDX passes the element's attributes as props using JavaScript names:
className(notclass; e.g."language-js"on a fenced code block'scode),href,title,src,alt,id, pluschildren. childrenis untyped (Mdx.children = Obj.t): a string, a Xote node, an array of those, or absent. Convert it withMdx.childrenToNodes(toarray<View.node>) orMdx.childrenToText(tostring). Never pattern-match on it directly.Mdx.childrenToNodes:null/undefined/booleans → nothing, arrays are flattened, Xote nodes pass through, anything else becomes a text node viaString(value).Mdx.childrenToText: concatenates strings and the text ofView.textnodes and fragments; other nodes (elements, reactive text) contribute"".- For plain elements (no override), the JSX runtime converts props:
className→class,htmlFor→for,ariaLabel/dataFoo-style camelCasearia*/data*→ kebab-case, astyleobject → akey:value;…string (camelCase keys to kebab-case, no units added), functions namedon[A-Z]…→ event listeners,null/undefinedprops → omitted, a function prop value on a non-event attribute → a reactive attribute, a signal → a reactive attribute. - 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.
- 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. - MDX can
importESM modules, including compiled ReScript output, e.g.import { make as Changelog } from "./Changelog.res.mjs".
API
| Name | Signature | Behaviour |
|---|---|---|
Mdx.children | Obj.t | Opaque children from the MDX runtime. |
Mdx.components (type) | dict<Obj.t => View.node> | Override map. |
Mdx.props | {components?: components} | Props every document accepts. |
Mdx.document | props => View.node | A compiled .mdx default export. |
Mdx.component | ('props => View.node) => Obj.t => View.node | Make a typed component usable as an override. |
Mdx.components (function) | array<(string, Obj.t => View.node)> => components | Build the override map. |
Mdx.render | (document, ~components: components=?, unit) => View.node | Render a document. |
Mdx.childrenToNodes | children => array<View.node> | Children as nodes. |
Mdx.childrenToText | children => string | Children as plain text. |
Patterns
Use to set up Vite for MDX:
1// vite.config.js2import mdx from "@mdx-js/rollup"3import remarkGfm from "remark-gfm"4import rehypeSlug from "rehype-slug"5import { defineConfig } from "vite"67export 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"23type linkProps = {href?: string, children?: Mdx.children}4type codeProps = {className?: string, children?: Mdx.children}56module 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}1819module 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}2627module Counter = {28 @xote.component29 let make = () => {30 let count = Signal.make(0)31 <button onClick={_ => Signal.update(count, n => n + 1)}> {"Clicked "} {Signal.get(count)} </button>32 }33}3435let components = Mdx.components([36 ("a", Mdx.component(Link.make)),37 ("code", Mdx.component(Code.make)),38 ("Counter", Mdx.component(Counter.make)),39])4041let 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 Vitetransformbefore MDX runs). rehype-slugids follow GitHub's slug rules; heading text with backticks or punctuation produces ids without them. Link targets MUST use the generated id.- A
refprop must be aView.Ref.tor a function; any other value (a React-style{current}object) is ignored with a console warning. - A
keyprop on an element produces a keyed node (View.Keyed). - An override for
prereceives the already-builtcodenode aschildren(a Xote node), not text; overridecodeto get the source text. componentsreplaces elements MDX creates from Markdown syntax (a paragraph becomesp, a linka, …) 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 whencomponentshas adiventry.
SSR and hydration
- A rendered MDX document is an ordinary node tree:
SSR.renderToStringrenders it on the server andHydration.hydrateByIdadopts it on the client, as long as both sides render the same document with the samecomponents. - Overrides and custom components follow normal server rules:
View.onMountfor 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 forreact/jsx-runtimemeansjsxImportSource: "xote"is missing. - Server test:
SSR.renderToString(() => Mdx.render(article, ~components, ()))and assert the expected HTML (overridden elements show your classes;classNamebecameclass). - 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.
Related
/docs/learn/components— writing the components used as overrides./docs/learn/routing—Router.linkfor internal links in overrides./docs/advanced/ssr— rendering MDX pages on the server./docs/api/view—View.node,View.fragment,View.text.