markdown-to-jsx

  • Version 9.11.0
  • Published
  • 4.06 MB
  • No dependencies
  • MIT license

Install

npm i markdown-to-jsx
yarn add markdown-to-jsx
pnpm add markdown-to-jsx

Overview

A very fast and versatile markdown toolchain. AST, React, React Native, SolidJS, Vue, Markdown, and HTML output available with full customization.

Index

Variables

variable compiler

var compiler: (
markdown?: string,
options?: Partial<{
createElement: (
tag: unknown,
props: React.JSX.IntrinsicAttributes,
...children: React.ReactNode[]
) => React.ReactNode;
disableFrontmatter: boolean;
disableAutoLink: boolean;
disableParsingRawHTML: boolean;
ignoreHTMLBlocks?: boolean;
tagfilter?: boolean;
enforceAtxHeadings: boolean;
evalUnserializableExpressions?: boolean;
forceBlock: boolean;
forceInline: boolean;
forceWrapper: boolean;
overrides: MarkdownToJSX.Overrides;
renderRule: (
next: () => React.ReactNode,
node: MarkdownToJSX.ASTNode,
renderChildren: MarkdownToJSX.ASTRender,
state: MarkdownToJSX.State
) => React.ReactNode;
sanitizer: (value: string, tag: string, attribute: string) => string;
slugify: (input: string, defaultFn: (input: string) => string) => string;
wrapper: any;
wrapperProps?: React.JSX.IntrinsicAttributes;
preserveFrontmatter?: boolean;
optimizeForStreaming?: boolean;
}>
) => React2.ReactNode;
  • Deprecated

    Use the markdown-to-jsx/react import instead

variable Markdown

var Markdown: React2.FC<
Omit<React2.HTMLAttributes<Element>, 'children'> & {
children?: string;
options?: Partial<{
createElement: (
tag: unknown,
props: React.JSX.IntrinsicAttributes,
...children: React.ReactNode[]
) => React.ReactNode;
disableFrontmatter: boolean;
disableAutoLink: boolean;
disableParsingRawHTML: boolean;
ignoreHTMLBlocks?: boolean;
tagfilter?: boolean;
enforceAtxHeadings: boolean;
evalUnserializableExpressions?: boolean;
forceBlock: boolean;
forceInline: boolean;
forceWrapper: boolean;
overrides: MarkdownToJSX.Overrides;
renderRule: (
next: () => React.ReactNode,
node: MarkdownToJSX.ASTNode,
renderChildren: MarkdownToJSX.ASTRender,
state: MarkdownToJSX.State
) => React.ReactNode;
sanitizer: (value: string, tag: string, attribute: string) => string;
slugify: (input: string, defaultFn: (input: string) => string) => string;
wrapper: any;
wrapperProps?: React.JSX.IntrinsicAttributes;
preserveFrontmatter?: boolean;
optimizeForStreaming?: boolean;
}>;
}
>;
  • Deprecated

    Use the markdown-to-jsx/react import instead

variable RuleType

const RuleType: {
readonly blockQuote: 0;
readonly breakLine: 1;
readonly breakThematic: 2;
readonly codeBlock: 3;
readonly codeInline: 4;
readonly footnote: 5;
readonly footnoteReference: 6;
readonly frontmatter: 7;
readonly gfmTask: 8;
readonly heading: 9;
readonly htmlBlock: 10;
readonly htmlComment: 11;
readonly htmlSelfClosing: 12;
readonly image: 13;
readonly link: 14;
readonly orderedList: 15;
readonly paragraph: 16;
readonly ref: 17;
readonly refCollection: 18;
readonly table: 19;
readonly text: 20;
readonly textFormatted: 21;
readonly unorderedList: 22;
};

    variable RuleTypeConst

    const RuleTypeConst: {
    readonly blockQuote: 0;
    readonly breakLine: 1;
    readonly breakThematic: 2;
    readonly codeBlock: 3;
    readonly codeInline: 4;
    readonly footnote: 5;
    readonly footnoteReference: 6;
    readonly frontmatter: 7;
    readonly gfmTask: 8;
    readonly heading: 9;
    readonly htmlBlock: 10;
    readonly htmlComment: 11;
    readonly htmlSelfClosing: 12;
    readonly image: 13;
    readonly link: 14;
    readonly orderedList: 15;
    readonly paragraph: 16;
    readonly ref: 17;
    readonly refCollection: 18;
    readonly table: 19;
    readonly text: 20;
    readonly textFormatted: 21;
    readonly unorderedList: 22;
    };
    • Analogous to node.type. Please note that the values here may change at any time, so do not hard code against the value directly.

    Functions

    function compiler

    compiler: (
    markdown?: string,
    options?: MarkdownToJSX.Options
    ) => React2.ReactNode;
    • Compile markdown string to React JSX elements

      Parameter markdown

      Markdown string to compile

      Parameter options

      Compiler options

      Returns

      React JSX element(s)

    function parser

    parser: (
    source: string,
    options?: ParserInputOptions | null
    ) => MarkdownToJSX.ASTNode[];
    • Main parser entry point.

    function sanitizer

    sanitizer: (input: string, tag?: string, attribute?: string) => string | null;
    • Sanitize URLs and other input values to prevent XSS attacks. Filters out javascript:, vbscript:, and data: URLs (except data:image), judged where a browser reads a scheme: before the first /, ?, or #. When the tag and attribute are given, an SVG data URL is also filtered out unless it fills an image slot (img src, img srcset, source src, source srcset, video poster, input src, image src, srcset, href, and xlink:href), since a browser runs its script when it opens the URL as a page.

      Parameter input

      The URL or value to sanitize

      Parameter tag

      The element the value is written to

      Parameter attribute

      The attribute the value is written to

      Returns

      Sanitized value, or null if unsafe

    function slugify

    slugify: (str: string) => string;
    • Convert a string to a URL-safe slug: ASCII letters are lowercased, digits are kept, spaces and dashes become hyphens, accented Latin letters map to their plain letter (é to e, č to c, ł to l, æ to a, ß to ss), and every other character is dropped, including non-Latin scripts.

      Parameter str

      String to slugify

      Returns

      URL-safe slug

    Type Aliases

    type RuleType

    type RuleType = RuleTypeValue;

      Namespaces

      namespace MarkdownToJSX

      namespace MarkdownToJSX {}
      • markdown-to-jsx types and interfaces

      interface BlockQuoteNode

      interface BlockQuoteNode {}
      • Blockquote node in the AST

      property alert

      alert?: string;
      • Optional alert type (Note, Tip, Warning, etc.)

      property children

      children: MarkdownToJSX.ASTNode[];
      • Child nodes within the blockquote

      property type

      type: typeof RuleType.blockQuote;

        interface BreakLineNode

        interface BreakLineNode {}
        • Hard line break node

        property type

        type: typeof RuleType.breakLine;

          interface BreakThematicNode

          interface BreakThematicNode {}
          • Thematic break (horizontal rule) node

          property type

          type: typeof RuleType.breakThematic;

            interface CodeBlockNode

            interface CodeBlockNode {}
            • Code block node (fenced code blocks)

            property attrs

            attrs?: React.JSX.IntrinsicAttributes;
            • HTML attributes for the code block

            property lang

            lang?: string;
            • Programming language identifier

            property text

            text: string;
            • Code content

            property type

            type: typeof RuleType.codeBlock;

              interface CodeInlineNode

              interface CodeInlineNode {}
              • Inline code node

              property text

              text: string;
              • Code text

              property type

              type: typeof RuleType.codeInline;

                interface FootnoteNode

                interface FootnoteNode {}
                • Footnote definition node (not rendered, stored in refCollection)

                property type

                type: typeof RuleType.footnote;

                  interface FootnoteReferenceNode

                  interface FootnoteReferenceNode {}
                  • Footnote reference node. The parser emits one only when the document defines the footnote, or while optimizeForStreaming is on.

                  property target

                  target: string;
                  • Link target (anchor)

                  property text

                  text: string;
                  • Display text

                  property type

                  type: typeof RuleType.footnoteReference;

                    interface FormattedTextNode

                    interface FormattedTextNode {}
                    • Formatted text node (bold, italic, etc.)

                    property children

                    children: MarkdownToJSX.ASTNode[];
                    • Child nodes

                    property tag

                    tag: string;
                    • the corresponding html tag

                    property type

                    type: typeof RuleType.textFormatted;

                      interface FrontmatterNode

                      interface FrontmatterNode {}
                      • YAML frontmatter node

                      property text

                      text: string;
                      • Frontmatter content

                      property type

                      type: typeof RuleType.frontmatter;

                        interface GFMTaskNode

                        interface GFMTaskNode {}
                        • GFM task list item node

                        property completed

                        completed: boolean;
                        • Whether the task is completed

                        property type

                        type: typeof RuleType.gfmTask;

                          interface HeadingNode

                          interface HeadingNode {}
                          • Heading node

                          property children

                          children: MarkdownToJSX.ASTNode[];
                          • Child nodes (text content)

                          property id

                          id: string;
                          • Generated HTML ID for anchor linking

                          property level

                          level: 1 | 2 | 3 | 4 | 5 | 6;
                          • Heading level (1-6)

                          property type

                          type: typeof RuleType.heading;

                            interface HTMLCommentNode

                            interface HTMLCommentNode {}
                            • HTML comment node

                            property text

                            text: string;
                            • Comment text

                            property type

                            type: typeof RuleType.htmlComment;

                              interface HTMLNode

                              interface HTMLNode {}
                              • HTML block node (includes JSX components)

                              property attrs

                              attrs?: Record<string, any>;
                              • Parsed HTML attributes

                              property children

                              children?: ASTNode[] | undefined;
                              • Parsed child nodes (always parsed, even for verbatim blocks)

                              property tag

                              tag: string;
                              • HTML tag name

                              property text

                              text?: string | undefined;
                              • Deprecated

                                This property will be removed in a future major version.

                              property type

                              type: typeof RuleType.htmlBlock;

                                interface HTMLSelfClosingNode

                                interface HTMLSelfClosingNode {}
                                • Self-closing HTML tag node

                                property attrs

                                attrs?: Record<string, any>;
                                • Parsed HTML attributes

                                property tag

                                tag: string;
                                • HTML tag name

                                property type

                                type: typeof RuleType.htmlSelfClosing;

                                  interface ImageNode

                                  interface ImageNode {}
                                  • Image node

                                  property alt

                                  alt?: string;
                                  • Alt text

                                  property target

                                  target: string | null;
                                  • Image URL. null when the destination was rejected by the URL sanitizer (compilers omit src / re-emit ![alt]()).

                                  property title

                                  title?: string;
                                  • Title attribute

                                  property type

                                  type: typeof RuleType.image;

                                    interface LinkNode

                                    interface LinkNode {}
                                    • Link node

                                    property children

                                    children: MarkdownToJSX.ASTNode[];
                                    • Child nodes (link text)

                                    property target

                                    target: string | null;
                                    • Link URL. null when the destination was rejected by the URL sanitizer (compilers omit href / re-emit [text]()). Missing reference definitions do not produce a link node at all.

                                    property title

                                    title?: string;
                                    • Title attribute

                                    property type

                                    type: typeof RuleType.link;

                                      interface OrderedListNode

                                      interface OrderedListNode {}
                                      • Ordered list node

                                      property items

                                      items: MarkdownToJSX.ASTNode[][];
                                      • Array of list items, each item is an array of nodes

                                      property start

                                      start?: number;
                                      • Starting number for the list

                                      property type

                                      type: typeof RuleType.orderedList;

                                        interface ParagraphNode

                                        interface ParagraphNode {}
                                        • Paragraph node

                                        property children

                                        children: MarkdownToJSX.ASTNode[];
                                        • Child nodes

                                        property type

                                        type: typeof RuleType.paragraph;

                                          interface ReferenceCollectionNode

                                          interface ReferenceCollectionNode {}
                                          • Reference collection node (appears at AST root, includes footnotes with '^' prefix)

                                          property refs

                                          refs: {
                                          [key: string]: {
                                          target: string;
                                          title: string | undefined;
                                          };
                                          };
                                          • Map of reference labels to their definitions; footnotes carry no title

                                          property type

                                          type: typeof RuleType.refCollection;

                                            interface ReferenceNode

                                            interface ReferenceNode {}
                                            • Reference definition node (not rendered, stored in refCollection)

                                            property type

                                            type: typeof RuleType.ref;

                                              interface State

                                              interface State {}
                                              • Parser and renderer state

                                              property inAnchor

                                              inAnchor?: boolean;
                                              • true if the current content is inside anchor link grammar

                                              property inBlockQuote

                                              inBlockQuote?: boolean;
                                              • true if inside a blockquote

                                              property inHTML

                                              inHTML?: boolean;
                                              • true if parsing in an HTML context

                                              property inline

                                              inline?: boolean;
                                              • true if parsing in an inline context (subset of rules around formatting and links)

                                              property inlineSafe

                                              inlineSafe?: boolean;
                                              • internal (react-native renderer): the enclosing subtree is already known inline-safe

                                              property inList

                                              inList?: boolean;
                                              • true if in a list

                                              property key

                                              key?: string | number;
                                              • use this for the key prop

                                              property refs

                                              refs?: {
                                              [key: string]: {
                                              target: string;
                                              title: string | undefined;
                                              };
                                              };
                                              • reference definitions (footnotes are stored with '^' prefix); footnotes carry no title

                                              property renderDepth

                                              renderDepth?: number;
                                              • current recursion depth during rendering

                                              interface TableNode

                                              interface TableNode {}
                                              • Table node

                                              property align

                                              align: Array<'left' | 'right' | 'center' | null>;
                                              • alignment for each table column

                                              property cells

                                              cells: MarkdownToJSX.ASTNode[][][];
                                              • Table cells (3D array: rows -> cells -> nodes)

                                              property header

                                              header: MarkdownToJSX.ASTNode[][];
                                              • Table header row

                                              property type

                                              type: typeof RuleType.table;

                                                interface TextNode

                                                interface TextNode {}
                                                • Plain text node

                                                property text

                                                text: string;
                                                • Text content

                                                property type

                                                type: typeof RuleType.text;

                                                  interface UnorderedListNode

                                                  interface UnorderedListNode {}
                                                  • Unordered list node

                                                  property items

                                                  items: MarkdownToJSX.ASTNode[][];
                                                  • Array of list items, each item is an array of nodes

                                                  property type

                                                  type: typeof RuleType.unorderedList;

                                                    type ASTNode

                                                    type ASTNode =
                                                    | BlockQuoteNode
                                                    | BreakLineNode
                                                    | BreakThematicNode
                                                    | CodeBlockNode
                                                    | CodeInlineNode
                                                    | FootnoteNode
                                                    | FootnoteReferenceNode
                                                    | FrontmatterNode
                                                    | GFMTaskNode
                                                    | HeadingNode
                                                    | HTMLCommentNode
                                                    | ImageNode
                                                    | LinkNode
                                                    | OrderedListNode
                                                    | UnorderedListNode
                                                    | ParagraphNode
                                                    | ReferenceNode
                                                    | ReferenceCollectionNode
                                                    | TableNode
                                                    | TextNode
                                                    | FormattedTextNode
                                                    | HTMLNode
                                                    | HTMLSelfClosingNode;
                                                    • Union type of all possible AST node types

                                                    type ASTRender

                                                    type ASTRender = (
                                                    ast: MarkdownToJSX.ASTNode | MarkdownToJSX.ASTNode[],
                                                    state?: MarkdownToJSX.State
                                                    ) => React.ReactNode;
                                                    • Function type for rendering AST nodes

                                                    type CreateElement

                                                    type CreateElement = typeof React.createElement;
                                                    • React.createElement function type

                                                    type HTMLTags

                                                    type HTMLTags = keyof React.JSX.IntrinsicElements & (string & {});
                                                    • HTML tag names that can be used in JSX

                                                    type Options

                                                    type Options = Partial<{
                                                    /**
                                                    * Ultimate control over the output of all rendered JSX.
                                                    */
                                                    createElement: (
                                                    tag: Parameters<CreateElement>[0],
                                                    props: React.JSX.IntrinsicAttributes,
                                                    ...children: React.ReactNode[]
                                                    ) => React.ReactNode;
                                                    /**
                                                    * Disable frontmatter detection at the start of the document.
                                                    * When `true`, `---` at position 0 will be parsed as a thematic break
                                                    * instead of being treated as a YAML frontmatter delimiter.
                                                    */
                                                    disableFrontmatter: boolean;
                                                    /**
                                                    * The library automatically generates an anchor tag for bare URLs included in the markdown
                                                    * document, but this behavior can be disabled if desired.
                                                    */
                                                    disableAutoLink: boolean;
                                                    /**
                                                    * Disable the compiler's best-effort transcription of provided raw HTML
                                                    * into JSX-equivalent. This is the functionality that prevents the need to
                                                    * use `dangerouslySetInnerHTML` in React.
                                                    */
                                                    disableParsingRawHTML: boolean;
                                                    /**
                                                    * Disable the compiler's parsing of HTML blocks.
                                                    */
                                                    ignoreHTMLBlocks?: boolean;
                                                    /**
                                                    * Enable GFM tagfilter extension to filter potentially dangerous HTML tags.
                                                    * When enabled, the following tags are escaped: title, textarea, style, xmp,
                                                    * iframe, noembed, noframes, script, plaintext.
                                                    * https://github.github.com/gfm/#disallowed-raw-html-extension-
                                                    * @default true
                                                    */
                                                    tagfilter?: boolean;
                                                    /**
                                                    * Requires a space or tab between the opening `#` characters and the heading
                                                    * text, as CommonMark and GFM do. Set to `false` to also read `#heading` as a
                                                    * heading; the markdown compiler then writes headings without the space.
                                                    * https://spec.commonmark.org/0.31.2/#atx-headings
                                                    * @default true
                                                    */
                                                    enforceAtxHeadings: boolean;
                                                    /**
                                                    * **⚠️ SECURITY WARNING: STRONGLY DISCOURAGED FOR USER INPUTS**
                                                    *
                                                    * When enabled, attempts to eval expressions in JSX props that cannot be serialized
                                                    * as JSON (functions, variables, complex expressions). This uses `eval()` which can
                                                    * execute arbitrary code.
                                                    *
                                                    * **ONLY use this option when:**
                                                    * - The markdown source is completely trusted (e.g., your own documentation)
                                                    * - You control all JSX components and their props
                                                    * - The content is NOT user-generated or user-editable
                                                    *
                                                    * **DO NOT use this option when:**
                                                    * - Processing user-submitted markdown
                                                    * - Rendering untrusted content
                                                    * - Building public-facing applications with user content
                                                    *
                                                    * Example unsafe input: `<Component onClick={() => fetch('/admin/delete-all')} />`
                                                    *
                                                    * Only a tag that starts with an uppercase letter and that `overrides` matches
                                                    * (ignoring case) has its props parsed or evaluated; every other tag keeps each
                                                    * attribute value as written.
                                                    *
                                                    * When disabled (default), unserializable expressions remain as strings that can be
                                                    * safely inspected or handled on a case-by-case basis via custom renderRule logic.
                                                    *
                                                    * @default false
                                                    */
                                                    evalUnserializableExpressions?: boolean;
                                                    /**
                                                    * Forces the compiler to always output content with a block-level wrapper
                                                    * (`<p>` or any block-level syntax your markdown already contains.)
                                                    */
                                                    forceBlock: boolean;
                                                    /**
                                                    * Forces the compiler to always output content with an inline wrapper (`<span>`)
                                                    */
                                                    forceInline: boolean;
                                                    /**
                                                    * Forces the compiler to wrap results, even if there is only a single
                                                    * child or no children.
                                                    */
                                                    forceWrapper: boolean;
                                                    /**
                                                    * Selectively control the output of particular HTML tags as they would be
                                                    * emitted by the compiler. A tag that starts with an uppercase letter matches
                                                    * a key ignoring case (exact key first, then the all-lowercase key, then the
                                                    * first key equal ignoring case); a lowercase tag matches its own key or its
                                                    * all-lowercase key. A capitalized tag with no match renders as an HTML tag.
                                                    */
                                                    overrides: Overrides;
                                                    /**
                                                    * Allows for full control over rendering of particular rules.
                                                    * For example, to implement a LaTeX renderer such as `react-katex`:
                                                    *
                                                    * ```
                                                    * renderRule(next, node, renderChildren, state) {
                                                    * if (node.type === RuleType.codeBlock && node.lang === 'latex') {
                                                    * return (
                                                    * <TeX as="div" key={state.key}>
                                                    * {String.raw`${node.text}`}
                                                    * </TeX>
                                                    * )
                                                    * }
                                                    *
                                                    * return next();
                                                    * }
                                                    * ```
                                                    */
                                                    renderRule: (
                                                    next: () => React.ReactNode,
                                                    node: ASTNode,
                                                    renderChildren: ASTRender,
                                                    state: State
                                                    ) => React.ReactNode;
                                                    /**
                                                    * Override the built-in sanitizer function for URLs, etc if desired. The built-in version is available as a library
                                                    * export called `sanitizer`.
                                                    */
                                                    sanitizer: (value: string, tag: string, attribute: string) => string | null;
                                                    /**
                                                    * Override normalization of non-URI-safe characters for use in generating
                                                    * HTML IDs for anchor linking purposes.
                                                    */
                                                    slugify: (input: string, defaultFn: (input: string) => string) => string;
                                                    /**
                                                    * Declare the type of the wrapper to be used when there are multiple
                                                    * children to render. Set to `null` to get an array of children back
                                                    * without any wrapper, or use `React.Fragment` to get a React element
                                                    * that won't show up in the DOM.
                                                    */
                                                    wrapper: React.ElementType | null;
                                                    /**
                                                    * Props to apply to the wrapper element.
                                                    */
                                                    wrapperProps?: React.JSX.IntrinsicAttributes;
                                                    /**
                                                    * Preserve frontmatter in the output by rendering it as a <pre> element.
                                                    * By default, frontmatter is parsed but not rendered.
                                                    * @default false
                                                    */
                                                    preserveFrontmatter?: boolean;
                                                    /**
                                                    * Optimize rendering for streaming scenarios where markdown content arrives
                                                    * incrementally (e.g., from LLM APIs). When enabled, incomplete inline syntax
                                                    * is suppressed to avoid displaying raw markdown characters while waiting
                                                    * for the closing delimiter to arrive.
                                                    *
                                                    * Fenced code blocks render normally with content visible as it streams.
                                                    *
                                                    * @default false
                                                    *
                                                    * @example
                                                    * ```tsx
                                                    * // Streaming markdown example
                                                    * function StreamingMarkdown({ content }) {
                                                    * return (
                                                    * <Markdown options={{ optimizeForStreaming: true }}>
                                                    * {content}
                                                    * </Markdown>
                                                    * )
                                                    * }
                                                    * ```
                                                    */
                                                    optimizeForStreaming?: boolean;
                                                    }>;
                                                    • Compiler options

                                                    type Override

                                                    type Override =
                                                    | RequireAtLeastOne<{
                                                    component: React.ElementType;
                                                    props: Object;
                                                    }>
                                                    | React.ElementType;
                                                    • Override configuration for HTML tags or custom components

                                                    type Overrides

                                                    type Overrides = { [tag in HTMLTags]?: Override } & {
                                                    [customComponent: string]: Override;
                                                    };
                                                    • Map of HTML tags and custom components to their override configurations

                                                    type RequireAtLeastOne

                                                    type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
                                                    T,
                                                    Exclude<keyof T, Keys>
                                                    > &
                                                    {
                                                    [K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>>;
                                                    }[Keys];
                                                    • RequireAtLeastOne<{ ... }> <- only requires at least one key

                                                    type TextFormattedNode

                                                    type TextFormattedNode = FormattedTextNode;
                                                    • Deprecated

                                                      Use FormattedTextNode instead.

                                                    Package Files (1)

                                                    Dependencies (0)

                                                    No dependencies.

                                                    Dev Dependencies (13)

                                                    Peer Dependencies (3)

                                                    Badge

                                                    To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                    You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/markdown-to-jsx.

                                                    • Markdown
                                                      [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/markdown-to-jsx)
                                                    • HTML
                                                      <a href="https://www.jsdocs.io/package/markdown-to-jsx"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>