markdown-to-jsx

  • Version 9.7.15
  • Published
  • 4.19 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?: MarkdownToJSX.Options
    ) => MarkdownToJSX.ASTNode[];
    • Main parser entry point - matches original parser interface

    function sanitizer

    sanitizer: (input: string) => string | null;
    • Sanitize URLs and other input values to prevent XSS attacks. Filters out javascript:, vbscript:, and data: URLs (except data:image).

      Parameter input

      The URL or value to sanitize

      Returns

      Sanitized value, or null if unsafe

    function slugify

    slugify: (str: string) => string;
    • Convert a string to a URL-safe slug by normalizing characters and replacing spaces with hyphens. Based on https://stackoverflow.com/a/18123682/1141611 Not complete, but probably good enough.

      Parameter str

      String to slugify

      Returns

      URL-safe slug

    Type Aliases

    type RuleType

    type RuleType2 = 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 RuleType2.blockQuote;

        interface BreakLineNode

        interface BreakLineNode {}
        • Hard line break node

        property type

        type: typeof RuleType2.breakLine;

          interface BreakThematicNode

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

          property type

          type: typeof RuleType2.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 RuleType2.codeBlock;

              interface CodeInlineNode

              interface CodeInlineNode {}
              • Inline code node

              property text

              text: string;
              • Code text

              property type

              type: typeof RuleType2.codeInline;

                interface FootnoteNode

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

                property type

                type: typeof RuleType2.footnote;

                  interface FootnoteReferenceNode

                  interface FootnoteReferenceNode {}
                  • Footnote reference node

                  property target

                  target: string;
                  • Link target (anchor)

                  property text

                  text: string;
                  • Display text

                  property type

                  type: typeof RuleType2.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 RuleType2.textFormatted;

                      interface FrontmatterNode

                      interface FrontmatterNode {}
                      • YAML frontmatter node

                      property text

                      text: string;
                      • Frontmatter content

                      property type

                      type: typeof RuleType2.frontmatter;

                        interface GFMTaskNode

                        interface GFMTaskNode {}
                        • GFM task list item node

                        property completed

                        completed: boolean;
                        • Whether the task is completed

                        property type

                        type: typeof RuleType2.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 RuleType2.heading;

                            interface HTMLCommentNode

                            interface HTMLCommentNode {}
                            • HTML comment node

                            property text

                            text: string;
                            • Comment text

                            property type

                            type: typeof RuleType2.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

                                Use _rawText instead. This property will be removed in a future major version.

                              property type

                              type: typeof RuleType2.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 RuleType2.htmlSelfClosing;

                                  interface ImageNode

                                  interface ImageNode {}
                                  • Image node

                                  property alt

                                  alt?: string;
                                  • Alt text

                                  property target

                                  target: string;
                                  • Image URL

                                  property title

                                  title?: string;
                                  • Title attribute

                                  property type

                                  type: typeof RuleType2.image;

                                    interface LinkNode

                                    interface LinkNode {}
                                    • Link node

                                    property children

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

                                    property target

                                    target: string | null;
                                    • Link URL (null for reference links without definition)

                                    property title

                                    title?: string;
                                    • Title attribute

                                    property type

                                    type: typeof RuleType2.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 RuleType2.orderedList;

                                        interface ParagraphNode

                                        interface ParagraphNode {}
                                        • Paragraph node

                                        property children

                                        children: MarkdownToJSX.ASTNode[];
                                        • Child nodes

                                        property type

                                        type: typeof RuleType2.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;
                                          };
                                          };
                                          • Map of reference labels to their definitions

                                          property type

                                          type: typeof RuleType2.refCollection;

                                            interface ReferenceNode

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

                                            property type

                                            type: typeof RuleType2.ref;

                                              interface TableNode

                                              interface TableNode {}
                                              • Table node

                                              property align

                                              align: ('left' | 'right' | 'center')[];
                                              • 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 RuleType2.table;

                                                interface TextNode

                                                interface TextNode {}
                                                • Plain text node

                                                property text

                                                text: string;
                                                • Text content

                                                property type

                                                type: typeof RuleType2.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 RuleType2.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;
                                                    /**
                                                    * Forces the compiler to have space between hash sign and the header text which
                                                    * is explicitly stated in the most of the markdown specs.
                                                    * https://github.github.com/gfm/#atx-heading
                                                    * `The opening sequence of # characters must be followed by a space or by the end of line.`
                                                    */
                                                    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')} />`
                                                    *
                                                    * 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.
                                                    */
                                                    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();
                                                    * }
                                                    * ```
                                                    *
                                                    * Thar be dragons obviously, but you can do a lot with this
                                                    * (have fun!) To see how things work internally, check the `render`
                                                    * method in source for a particular rule.
                                                    */
                                                    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 State

                                                    type State = {
                                                    /** true if the current content is inside anchor link grammar */
                                                    inAnchor?: boolean;
                                                    /** true if inside a blockquote */
                                                    inBlockQuote?: boolean;
                                                    /** true if parsing in an HTML context */
                                                    inHTML?: boolean;
                                                    /** true if in a list */
                                                    inList?: boolean;
                                                    /** true if parsing in an inline context (subset of rules around formatting and links) */
                                                    inline?: boolean;
                                                    /** use this for the `key` prop */
                                                    key?: string | number;
                                                    /** reference definitions (footnotes are stored with '^' prefix) */
                                                    refs?: {
                                                    [key: string]: {
                                                    target: string;
                                                    title: string;
                                                    };
                                                    };
                                                    /** current recursion depth during rendering */
                                                    renderDepth?: number;
                                                    /** internal: block parse recursion depth */
                                                    _depth?: number;
                                                    /** internal: disable setext heading detection (lazy blockquote continuation) */
                                                    _noSetext?: boolean;
                                                    /** internal: HTML nesting depth for stack overflow protection */
                                                    _htmlDepth?: number;
                                                    /** internal: set by collectReferenceDefinitions when input ends inside an unclosed fence */
                                                    _endsInsideFence?: boolean;
                                                    };
                                                    • Parser and renderer state

                                                    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>