### Run Example App Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/README.md Navigate to the example directory, install its dependencies, and start the Expo development server to explore the library's features. ```sh cd example npm install npx expo start ``` -------------------------------- ### Install react-native-markdown-renderer with npm Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/Getting-Started Use this command to install the library via npm. ```sh npm install react-native-markdown-renderer ``` -------------------------------- ### Install react-native-markdown-renderer with yarn Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/Getting-Started Use this command to install the library via yarn. ```sh yarn add react-native-markdown-renderer ``` -------------------------------- ### Custom AstRenderer with Styles and Options Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/wiki/Custom-Renderer.md Example of creating a custom `AstRenderer` with specific styles and an `onLinkPress` handler. This renderer can then be passed to the `Markdown` component. ```tsx import Markdown, { AstRenderer, renderRules, styles as defaultStyles, } from 'react-native-markdown-renderer'; const customStyles = { ...defaultStyles, heading1: { fontSize: 32, backgroundColor: '#000000', color: '#FFFFFF', }, heading: { fontWeight: '600', borderBottomWidth: 1, borderColor: '#000000', }, }; const renderer = new AstRenderer(renderRules, customStyles, { onLinkPress: (url) => { console.log('Link pressed:', url); }, }); const App = () => ( {'# Custom rendered heading'} ); ``` -------------------------------- ### Custom Renderer Setup in v4 Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/Migration-from-v3 Instantiate a custom `AstRenderer` with specific rules and styles for advanced rendering control. The `AstRenderer` was imported but not typically used in v3. ```jsx import Markdown, { AstRenderer } from 'react-native-markdown-renderer'; // AstRenderer was imported but not typically used {copy} ``` ```tsx import Markdown, { AstRenderer, renderRules, styles as defaultStyles } from 'react-native-markdown-renderer'; const customStyles = { ...defaultStyles, heading1: { fontSize: 32 } }; const renderer = new AstRenderer(renderRules, customStyles); {copy} ``` -------------------------------- ### Integrate markdown-it Plugins Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/README.md Extend markdown parsing capabilities by passing an array of `PluginContainer` instances to the `plugins` prop. This example uses `markdown-it-checkbox`. ```tsx import Markdown, { PluginContainer } from 'react-native-markdown-renderer'; import markdownItCheckbox from 'markdown-it-checkbox'; const plugins = [new PluginContainer(markdownItCheckbox)]; const App = () => ( {'- [ ] Unchecked\n- [x] Checked'} ); ``` -------------------------------- ### Custom Heading1 Rule Example Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/Custom-Rules Replace the default rendering for heading1 elements by providing a custom function to the 'rules' prop. This example wraps the heading text in brackets. ```tsx import React from 'react'; import { Text } from 'react-native'; import Markdown from 'react-native-markdown-renderer'; import type { ASTNode, RenderRules, MarkdownStyles } from 'react-native-markdown-renderer'; import type { ReactNode } from 'react'; const rules: Partial = { heading1: (node: ASTNode, children: ReactNode[], _parent: ASTNode[], styles: MarkdownStyles) => ( [{children}] ), }; const App = () => ( {'# This heading will be wrapped in brackets'} ); ``` -------------------------------- ### Configure Linkify Feature in MarkdownIt Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/Examples Configure the linkify-it library within MarkdownIt to customize TLDs, add/disable protocols, and enable fuzzy IP matching. This setup is useful for advanced URL detection and handling. ```jsx const md = Markdownit({ typographer: true, linkify: true, }); md.linkify.tlds('.py', false); // disables .py as top level domain md.linkify.tlds('onion', true) // Add unofficial `.onion` domain md.linkify.add('git:', 'http:') // Add `git:` protocol as "alias" md.linkify.add('ftp:', null) // Disable `ftp:` ptotocol md.linkify.set({ fuzzyIP: true }); // Enable IPs in fuzzy links (without schema) // add twitter mention handler see https://github.com/markdown-it/linkify-it#example-2-add-twitter-mentions-handler where this is from. md.linkify.add('@', { validate: function (text, pos, self) { var tail = text.slice(pos); if (!self.re.twitter) { self.re.twitter = new RegExp( '^([a-zA-Z0-9_]){1,15}(?!_)(?=$|' + self.re.src_ZPCc + ')' ); } if (self.re.twitter.test(tail)) { // Linkifier allows punctuation chars before prefix, // but we additionally disable `@` ("@@mention" is invalid) if (pos >= 2 && tail[pos - 2] === '@') { return false; } return tail.match(self.re.twitter)[0].length; } return 0; }, normalize: function (match) { match.url = 'https://twitter.com/' + match.url.replace(/^@/, ''); } }); export default class Page extends PureComponent { render() { return ( {copy} ); } } ``` -------------------------------- ### Integrate markdown-it Checkbox Plugin Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/Plugins Use the `PluginContainer` to wrap a markdown-it plugin and pass it to the `plugins` prop. This example shows how to integrate the `markdown-it-checkbox` plugin. ```tsx import Markdown, { PluginContainer } from 'react-native-markdown-renderer'; import markdownItCheckbox from 'markdown-it-checkbox'; const plugins = [new PluginContainer(markdownItCheckbox)]; const App = () => ( {'- [ ] Unchecked\n- [x] Checked'} ); ``` -------------------------------- ### Render Markdown Code Block in React Native Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/example/example_test.md This snippet demonstrates how to render a basic Markdown code block. Ensure the library is correctly installed and imported. ```javascript const greeting = "Hello, Markdown!"; console.log(greeting); ``` -------------------------------- ### `AstRenderer` Class Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/wiki/API-Reference.md Combines render rules, styles, and options into a renderer. It provides methods to get render functions for specific node types, render individual nodes, and render a full AST. ```APIDOC ## `AstRenderer` Class ### Description Combines render rules, styles, and options into a renderer. The optional `options` parameter configures link handling, image validation, debug logging, and preview mode. See [Custom Renderer](Custom-Renderer). ### Constructor ```tsx constructor(renderRules: RenderRules, style?: MarkdownStyles, options?: AstRendererOptions); ``` ### Methods - `getRenderFunction(type: string): RenderFunction` - `renderNode(node: ASTNode, parentNodes: ASTNode[]): ReactNode` - `render(nodes: ASTNode[]): ReactElement` ``` -------------------------------- ### Custom Rendering Rules for Markdown Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/Examples Overrides default markdown rendering rules to customize the appearance of specific markdown elements. This example customizes headings to be enclosed in brackets. ```jsx import react from 'react'; import {View, PureComponent, Text} from 'react-native'; import Markdown, {getUniqueID} from 'react-native-markdown-renderer'; const rules = { heading1: (node, children, parent, styles) => [{children}] , heading2: (node, children, parent, styles) => [{children}] , heading3: (node, children, parent, styles) => [{children}] , }); const copy = ` # h1 Heading 8-) ## h2 Heading 8-) ### h3 Heading 8-) | Option | Description | | ------ | ----------- | | data | path to data files to supply the data that will be passed into templates. | | engine | engine to be used for processing templates. Handlebars is the default. | | ext | extension to be used for dest files. | `; export default class Page extends PureComponent { render() { return ( {copy} ); } } ``` -------------------------------- ### Instantiate MarkdownIt Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference Re-exports the markdown-it constructor for convenience. Use this to create a custom markdown-it instance with specific configurations. ```tsx import { MarkdownIt } from 'react-native-markdown-renderer'; const md = new MarkdownIt({ typographer: true }); ``` -------------------------------- ### Instantiate MarkdownIt Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/wiki/API-Reference.md Re-exports the markdown-it constructor for convenience. Use this to create a custom markdown-it instance. ```tsx import { MarkdownIt } from 'react-native-markdown-renderer'; const md = new MarkdownIt({ typographer: true }); ``` -------------------------------- ### Basic Markdown Rendering Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/Examples Demonstrates the most basic implementation of the Markdown component. Import the component and pass your markdown string as children. ```javascript import react from 'react'; import {PureComponent} from 'react-native'; import Markdown from 'react-native-markdown-renderer'; const copy = `# h1 Heading 8-) | Option | Description | | ------ | ----------- | | data | path to data files to supply the data that will be passed into templates. | | engine | engine to be used for processing templates. Handlebars is the default. | | ext | extension to be used for dest files. | `; export default class Page extends PureComponent { static propTypes = {}; static defaultProps = {}; render() { return ( {copy} ); } } ``` -------------------------------- ### Initialize AstRenderer Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/Custom-Renderer Instantiate AstRenderer with default render rules and styles. ```tsx import { AstRenderer, renderRules, styles } from 'react-native-markdown-renderer'; const renderer = new AstRenderer(renderRules, styles); ``` -------------------------------- ### Configure Plugin with Options Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/Plugins Pass configuration options to a plugin by including them as arguments after the plugin in the `PluginContainer` constructor. This allows for customization of plugin behavior. ```tsx const plugins = [ new PluginContainer(somePlugin, { option1: true, option2: 'value' }), ]; ``` -------------------------------- ### Instantiate AstRenderer Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/wiki/Custom-Renderer.md Create an `AstRenderer` instance by passing render rules and styles. Options can be provided for advanced configuration like link handling and debug logging. ```tsx import { AstRenderer, renderRules, styles } from 'react-native-markdown-renderer'; const renderer = new AstRenderer(renderRules, styles); // With options (v4.1.0+): const renderer = new AstRenderer(renderRules, styles, { onLinkPress: (url) => console.log('Link:', url), debugPrintTree: false, maxTopLevelChildren: null, allowedImageHandlers: ['https://', 'http://', 'data:image/png;base64'], defaultImageHandler: 'http://', }); ``` -------------------------------- ### Use Multiple Plugins Simultaneously Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/Plugins You can integrate multiple markdown-it plugins by adding each one as a separate `PluginContainer` instance to the `plugins` array. Options can be provided to individual plugins as needed. ```tsx const plugins = [ new PluginContainer(pluginA), new PluginContainer(pluginB, { optionB: true }), new PluginContainer(pluginC), ]; ``` -------------------------------- ### Integrating markdown-it Plugins Source: https://context7.com/mientjan/react-native-markdown-renderer/llms.txt Wrap any markdown-it plugin in `PluginContainer` and pass it through the `plugins` prop to extend Markdown rendering capabilities. Options are forwarded to the plugin via rest arguments. ```tsx import React from 'react'; import Markdown, { PluginContainer } from 'react-native-markdown-renderer'; import markdownItCheckbox from 'markdown-it-checkbox'; import markdownItSup from 'markdown-it-sup'; import markdownItSub from 'markdown-it-sub'; // PluginContainer(plugin, ...optionalArgs) const plugins = [ new PluginContainer(markdownItCheckbox, { divWrap: false }), new PluginContainer(markdownItSup), new PluginContainer(markdownItSub), ]; const content = "\n- [ ] Task not done\n- [x] Task completed\n\nH^2^O is water. CO~2~ is carbon dioxide.\n"; export default function PluginsExample() { return ( {content} ); } ``` -------------------------------- ### Full Custom AST Renderer with Options Source: https://context7.com/mientjan/react-native-markdown-renderer/llms.txt Take full control of rendering by passing a pre-built `AstRenderer` instance. When `renderer` is set, `rules` and `style` props are ignored. This allows for deep customization of styles and behavior, including link press handling and image handling. ```tsx import React from 'react'; import { ScrollView, StyleSheet } from 'react-native'; import Markdown, { AstRenderer, renderRules, styles as defaultStyles, } from 'react-native-markdown-renderer'; import type { AstRendererOptions } from 'react-native-markdown-renderer'; // Compose custom styles on top of defaults const customStyles = { ...defaultStyles, heading1: { fontSize: 36, color: '#fff', backgroundColor: '#0969da', padding: 10 }, heading2: { fontSize: 26, color: '#0969da' }, codeBlock: { backgroundColor: '#1e1e1e', padding: 16, borderRadius: 8 }, }; const options: AstRendererOptions = { onLinkPress: (url) => { console.log('Link pressed:', url); // return true to prevent default Linking.openURL behavior }, debugPrintTree: false, maxTopLevelChildren: null, allowedImageHandlers: ['https://', 'data:image/png;base64'], defaultImageHandler: null, // skip images that don't match }; const renderer = new AstRenderer(renderRules, customStyles, options); export default function CustomRendererExample() { return ( {`# Custom Renderer\n\n## Subtitle\n\nSome **bold** and *italic* text.\n\n\ ```js\nconsole.log('hello');\n\ ```}`} ); } ``` -------------------------------- ### Create Custom AstRenderer with Styles Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/Custom-Renderer Combine default styles with custom styles to create a new AstRenderer instance for customized markdown rendering. ```tsx import Markdown, { AstRenderer, renderRules, styles as defaultStyles, } from 'react-native-markdown-renderer'; const customStyles = { ...defaultStyles, heading1: { fontSize: 32, backgroundColor: '#000000', color: '#FFFFFF', }, heading: { fontWeight: '600', borderBottomWidth: 1, borderColor: '#000000', }, }; const renderer = new AstRenderer(renderRules, customStyles); const App = () => ( {'# Custom rendered heading'} ); ``` -------------------------------- ### Re-export: `MarkdownIt` Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference The `markdown-it` constructor is re-exported for convenience, allowing direct instantiation of a markdown-it parser. ```APIDOC ## Re-export: `MarkdownIt` ### Description The `markdown-it` constructor, re-exported for convenience. ### Example ```tsx import { MarkdownIt } from 'react-native-markdown-renderer'; const md = new MarkdownIt({ typographer: true }); ``` ``` -------------------------------- ### Custom markdown-it Instance Configuration Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/Plugins For complete control over the markdown parsing process, create and configure a `markdown-it` instance manually. Pass this custom instance to the `markdownit` prop of the `Markdown` component. ```tsx import Markdown from 'react-native-markdown-renderer'; import MarkdownIt from 'markdown-it'; const md = new MarkdownIt({ html: true, linkify: true }) .use(somePlugin) .use(anotherPlugin, { option: true }); const App = () => ( {'# Custom parser configuration'} ); ``` -------------------------------- ### AST Debug Logging with `debugPrintTree` Source: https://context7.com/mientjan/react-native-markdown-renderer/llms.txt Enable logging of the full Abstract Syntax Tree (AST) node hierarchy to the console during rendering. Each line is prefixed with dashes indicating nesting depth. ```tsx import Markdown from 'react-native-markdown-renderer'; // Console output example: // bullet_list // -list_item // --paragraph // ---textgroup // ----text export default function DebugExample() { return ( {'- Item one - Item two **Bold** and *italic*'} ); } ``` -------------------------------- ### AstRenderer Constructor Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/wiki/Custom-Renderer.md The AstRenderer class combines render rules and styles into a single renderer instance. It can be initialized with render rules, optional styles, and configuration options. ```APIDOC ## AstRenderer Constructor ### Description Initializes an AstRenderer instance with custom render rules, styles, and options. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Signature ```tsx new AstRenderer(renderRules: RenderRules, styles?: MarkdownStyles, options?: AstRendererOptions) ``` ### Parameters Details - **`renderRules`** (`RenderRules`) - Object mapping node types to render functions. - **`styles`** (`MarkdownStyles`, optional) - Styles passed to every render function. - **`options`** (`AstRendererOptions`, optional) - Configuration for link handling, image validation, debug logging, and preview mode. #### `AstRendererOptions` Details - **`onLinkPress`** (`(url: string) => boolean | void`, optional) - Custom link press handler. - **`debugPrintTree`** (`boolean`, optional, default: `false`) - Log depth-prefixed node types during rendering. - **`maxTopLevelChildren`** (`number | null`, optional, default: `null`) - Limit top-level rendered children. - **`topLevelMaxExceededItem`** (`ReactNode`, optional, default: `...`) - Shown when limit is exceeded. - **`allowedImageHandlers`** (`string[]`, optional, default: `['data:image/png;base64', ..., 'https://', 'http://']`) - Allowed image URL prefixes. - **`defaultImageHandler`** (`string | null`, optional, default: `'http://'`) - Prepended to unrecognized image URLs. `null` to skip. ### Request Example ```tsx import { AstRenderer, renderRules, styles } from 'react-native-markdown-renderer'; const renderer = new AstRenderer(renderRules, styles, { onLinkPress: (url) => console.log('Link:', url), debugPrintTree: false, maxTopLevelChildren: null, allowedImageHandlers: ['https://', 'http://', 'data:image/png;base64'], defaultImageHandler: 'http://', }); ``` ``` -------------------------------- ### Creating Custom Block Syntax with blockPlugin Source: https://context7.com/mientjan/react-native-markdown-renderer/llms.txt Register custom block-level container syntax (e.g., `[name]...[/name]`) using the `blockPlugin` factory. Useful for custom elements like callouts or warning blocks. ```tsx import { MarkdownIt, PluginContainer, blockPlugin } from 'react-native-markdown-renderer'; import Markdown from 'react-native-markdown-renderer'; // Register a custom [tip]...[/tip] block const md = new MarkdownIt({ typographer: true }); md.use(blockPlugin, 'tip', { marker: '[tip]', marker_end: '[/tip]', validate: (params: string) => params.trim().startsWith('tip'), }); export default function BlockPluginExample() { return ( {`[tip]\nThis is a custom tip block.\n[/tip]`} ); } ``` -------------------------------- ### `openUrl` Function Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference Opens a given URL using React Native's Linking API. ```APIDOC ## `openUrl` Function ### Description Opens a URL using React Native's `Linking` API. Used by the default `link` render rule. ### Parameters - `url` (string) - The URL to open. ``` -------------------------------- ### `tokensToAST` Function Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference Converts an array of markdown-it tokens into the library's Abstract Syntax Tree (AST) format. ```APIDOC ## `tokensToAST` Function ### Description Converts markdown-it tokens to the library's AST format. ### Parameters - `tokens` (Token[]) - An array of markdown-it tokens. ### Returns - `ASTNode[]` - An array of AST nodes. ``` -------------------------------- ### `styles` Object Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference The default object containing styles for markdown elements. ```APIDOC ## `styles` Object ### Description The default styles object. See [Custom Styles](Custom-Styles) for all available keys. ``` -------------------------------- ### `styles` Object Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/wiki/API-Reference.md The default styles object, providing default styling for markdown elements. Refer to the [Custom Styles](Custom-Styles) documentation for a list of all available style keys. ```APIDOC ## `styles` Object ### Description The default styles object. See [Custom Styles](Custom-Styles) for all available keys. ``` -------------------------------- ### Safe URL Opening with `openUrl` Source: https://context7.com/mientjan/react-native-markdown-renderer/llms.txt Use the `openUrl` utility to safely open URLs with `Linking.openURL()`, including a check to prevent opening non-HTTPS URLs. This is useful for custom link render rules. ```tsx import React from 'react'; import { Text } from 'react-native'; import { openUrl } from 'react-native-markdown-renderer'; import type { ASTNode, RenderRules } from 'react-native-markdown-renderer'; const customRules: Partial = { link: (node: ASTNode, children, _parent, styles) => { const url = node.attributes.href; return ( { if (url.startsWith('https://')) { openUrl(url); } else { console.warn('Blocked non-HTTPS URL:', url); } }} > {children} ); }, }; import Markdown from 'react-native-markdown-renderer'; export default function OpenUrlExample() { return ( {'[Safe link](https://example.com)\n\n[Blocked link](ftp://files.example.com)'} ); } ``` -------------------------------- ### Preview Mode with `maxTopLevelChildren` and `topLevelMaxExceededItem` Source: https://context7.com/mientjan/react-native-markdown-renderer/llms.txt Limit the number of top-level block elements rendered. Use `topLevelMaxExceededItem` to provide a custom node that replaces truncated content. ```tsx import React from 'react'; import { Text, TouchableOpacity } from 'react-native'; import Markdown from 'react-native-markdown-renderer'; const longContent = ` # Article Title First paragraph with introductory text. Second paragraph with more detail. Third paragraph — this and beyond are hidden in preview. Fourth paragraph. Fifth paragraph. `; export default function PreviewMode({ onReadMore }: { onReadMore: () => void }) { return ( Read more… } > {longContent} ); } // Renders: heading + first paragraph, then the "Read more…" button ``` -------------------------------- ### `renderRules` Object Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference The default object containing render functions for all supported markdown node types. ```APIDOC ## `renderRules` Object ### Description The default render rules object. Contains render functions for all supported node types. Useful as a base when creating a custom `AstRenderer`. ``` -------------------------------- ### Custom Markdown Parser with `markdownit` Source: https://context7.com/mientjan/react-native-markdown-renderer/llms.txt Inject a pre-configured `MarkdownIt` instance to control parser behavior, such as enabling typographer, HTML passthrough, linkify, and line breaks. ```tsx import Markdown, { MarkdownIt } from 'react-native-markdown-renderer'; // Enable HTML passthrough and linkify const customMd = new MarkdownIt({ typographer: true, html: true, linkify: true, breaks: true, }); export default function CustomParserExample() { return ( {'Auto-link: https://example.com Line break here.'} ); } ``` -------------------------------- ### `PluginContainer` Class Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference A utility class to wrap a markdown-it plugin and its options. ```APIDOC ## `PluginContainer` Class ### Description Wraps a markdown-it plugin and its options. See [Plugins](Plugins). ### Constructor - `constructor(plugin: T, ...options: unknown[])` ### Methods - `toArray(): [T, ...unknown[]]` Returns the plugin and its options as an array. ``` -------------------------------- ### Import TypeScript Definitions Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/README.md Import necessary types and components from the library for TypeScript projects. This includes render rules, styles, and plugin containers. ```tsx import Markdown, { AstRenderer, renderRules, styles, PluginContainer, type MarkdownProps, type RenderRules, type ASTNode, type RenderFunction, type MarkdownStyles, } from 'react-native-markdown-renderer'; ``` -------------------------------- ### RenderRules Interface Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/wiki/API-Reference.md An interface representing a collection of render functions, keyed by rule names. This allows for custom rendering logic for different markdown elements. ```APIDOC ## RenderRules Interface ### Description An interface representing a collection of render functions, keyed by rule names. This allows for custom rendering logic for different markdown elements. ### Interface Definition ```typescript interface RenderRules { [name: string]: RenderFunction; } ``` ``` -------------------------------- ### `` Component Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference The primary component for rendering markdown content. It accepts markdown strings and converts them into native React Native elements. ```APIDOC ## `` Component ### Description The default export. A function component that renders markdown as native React Native elements. ### Props #### `children` (string | string[]) - Required Markdown content to render. #### `rules` (Partial) - Optional, Default: `{}` Custom render rules merged with defaults. #### `style` (Partial) - Optional, Default: `{}` Custom styles merged with defaults. #### `renderer` (AstRenderer | ((nodes: ASTNode[]) => ReactElement)) - Optional Fully custom renderer (overrides `rules` and `style`). #### `markdownit` (MarkdownIt) - Optional, Default: `MarkdownIt({ typographer: true })` Custom markdown-it instance. #### `plugins` (PluginContainer[]) - Optional, Default: `[]` markdown-it plugins. ``` -------------------------------- ### How Style Merging Works Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/Custom-Styles Illustrates the internal mechanism of style merging, where custom styles are applied on top of default styles. ```tsx // Inside the Markdown component: new AstRenderer( { ...defaultRenderRules, ...rules }, { ...defaultStyles, ...style } ); ``` -------------------------------- ### Managing Markdown-it Plugins with PluginContainer Source: https://context7.com/mientjan/react-native-markdown-renderer/llms.txt Wrap markdown-it plugins for serialization. The `` component uses `plugin.toArray()` to apply plugins. Supports plugins with or without options. ```tsx import { PluginContainer } from 'react-native-markdown-renderer'; import markdownItAbbr from 'markdown-it-abbr'; import markdownItFootnote from 'markdown-it-footnote'; import markdownItContainer from 'markdown-it-container'; // Plugin with no options const abbrPlugin = new PluginContainer(markdownItAbbr); // Plugin with options const containerPlugin = new PluginContainer(markdownItContainer, 'warning', { render: (tokens: any[], idx: number) => tokens[idx].nesting === 1 ? ' ', }); // Inspect the wrapped array console.log(abbrPlugin.toArray()); // [markdownItAbbr] console.log(containerPlugin.toArray()); // [markdownItContainer, 'warning', { render: fn }] // Use in component import Markdown from 'react-native-markdown-renderer'; export default function Example() { return ( {'*[HTML]: Hyper Text Markup Language HTML is awesome.'} ); } ``` -------------------------------- ### Low-level Parser Function Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/wiki/API-Reference.md Tokenizes the source string and passes the AST to the renderer. ```tsx function parser( source: string, renderer: (nodes: ASTNode[]) => ReactElement, markdownIt: MarkdownIt ): ReactElement; ``` -------------------------------- ### `applyStyle` Function Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference Applies specified styles to child elements that match a given component type. ```APIDOC ## `applyStyle` Function ### Description Applies styles to child elements matching the given component type. ### Parameters - `children` (ReactElement[]) - The child elements to style. - `styles` (unknown[]) - An array of styles to apply. - `targetType` (string) - The type of component to apply styles to. ### Returns - `ReactElement[]` - The styled child elements. ``` -------------------------------- ### Configure Allowed Image Handlers Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/README.md Control which image URL schemes are permitted. Unrecognized schemes are skipped if `defaultImageHandler` is `null`, or processed by the default handler otherwise. ```tsx {'![photo](https://example.com/photo.png)'} ``` -------------------------------- ### Function Renderer Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/wiki/Custom-Renderer.md A function can be passed directly as a renderer. This function receives the parsed AST nodes and must return a ReactElement. ```APIDOC ## Function Renderer ### Description Provides a custom rendering function that takes AST nodes and returns React elements. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Function Signature ```tsx function myRenderer(nodes: ASTNode[]): ReactElement ``` ### Parameters Details - **`nodes`** (`ASTNode[]`) - An array of AST nodes to be rendered. ### Return Value - `ReactElement` - The rendered React element. ### Request Example ```tsx import Markdown from 'react-native-markdown-renderer'; import { Text, View } from 'react-native'; import type { ASTNode } from 'react-native-markdown-renderer'; function myRenderer(nodes: ASTNode[]) { return ( {nodes.map((node) => ( {node.content || node.type} ))} ); } const App = () => ( {'# Hello'} ); ``` ``` -------------------------------- ### Render Markdown with Default Component Source: https://context7.com/mientjan/react-native-markdown-renderer/llms.txt Use the `` component to render raw markdown strings as native React Native elements. Ensure necessary imports and provide markdown content as children. ```tsx import React from 'react'; import { ScrollView } from 'react-native'; import Markdown from 'react-native-markdown-renderer'; const content = `# Hello World This is **bold**, *italic*, and ~~strikethrough~~ text. > A blockquote with inline code const x = 42; | Name | Age | |-------|-----| | Alice | 30 | | Bob | 25 | - Unordered item - Another item 1. First 2. Second [Visit Example](https://example.com) ![Logo](https://example.com/logo.png) `; export default function App() { return ( {content} ); } ``` -------------------------------- ### PluginContainer Class Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/wiki/API-Reference.md Wraps a markdown-it plugin and its options. See [Plugins](Plugins). ```tsx class PluginContainer { constructor(plugin: T, ...options: unknown[]); toArray(): [T, ...unknown[]]; } ``` -------------------------------- ### AstRenderer Class Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/wiki/API-Reference.md Combines render rules, styles, and options into a renderer. The optional `options` parameter configures link handling, image validation, debug logging, and preview mode. ```tsx class AstRenderer { constructor(renderRules: RenderRules, style?: MarkdownStyles, options?: AstRendererOptions); getRenderFunction(type: string): RenderFunction; renderNode(node: ASTNode, parentNodes: ASTNode[]): ReactNode; render(nodes: ASTNode[]): ReactElement; } ``` -------------------------------- ### Customize Link Press Behavior Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/README.md Intercept link presses using the `onLinkPress` prop to implement custom navigation or logging logic. Returning nothing prevents the default `Linking.openURL()` behavior. ```tsx const App = () => ( { console.log('Link pressed:', url); // return nothing to prevent default behavior }}> {'[Visit Example](https://example.com)'} ); ``` -------------------------------- ### MarkdownProps Interface Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/wiki/API-Reference.md Props for the main Markdown component, including content, custom rules, styles, and renderer options. ```APIDOC ## MarkdownProps Interface ### Description Props for the main Markdown component, including content, custom rules, styles, and renderer options. ### Interface Definition ```typescript interface MarkdownProps { children: string | string[]; rules?: RenderRules; style?: Partial; mergeStyle?: boolean; renderer?: AstRenderer | ((nodes: ASTNode[]) => ReactElement); markdownit?: MarkdownIt; plugins?: PluginContainer[]; onLinkPress?: (url: string) => boolean | void; debugPrintTree?: boolean; maxTopLevelChildren?: number | null; topLevelMaxExceededItem?: ReactNode; allowedImageHandlers?: string[]; defaultImageHandler?: string | null; } ``` ``` -------------------------------- ### Open URL Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference Opens a URL using React Native's Linking API. This is used by the default link render rule to handle external links. ```tsx function openUrl(url: string): void; ``` -------------------------------- ### PluginContainer Class Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference Wraps a markdown-it plugin and its options. This is useful for integrating custom markdown-it plugins with the renderer. ```tsx class PluginContainer { constructor(plugin: T, ...options: unknown[]); toArray(): [T, ...unknown[]]; } ``` -------------------------------- ### `AstRenderer` Class Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference A class that combines render rules and styles to create a custom renderer for markdown AST nodes. ```APIDOC ## `AstRenderer` Class ### Description Combines render rules and styles into a renderer. See [Custom Renderer](Custom-Renderer). ### Constructor - `constructor(renderRules: RenderRules, style?: MarkdownStyles)` ### Methods - `getRenderFunction(type: string): RenderFunction` Gets the render function for a specific node type. - `renderNode(node: ASTNode, parentNodes: ASTNode[]): ReactNode` Renders a single AST node. - `render(nodes: ASTNode[]): ReactElement` Renders an array of AST nodes. ``` -------------------------------- ### Default Render Rules Object Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/wiki/API-Reference.md The default render rules object. Contains render functions for all supported node types. Useful as a base when creating a custom `AstRenderer`. ```tsx const renderRules: RenderRules; ``` -------------------------------- ### Implement a Function Renderer Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/Custom-Renderer Pass a custom function directly to the renderer prop to handle AST node rendering. This function receives nodes and must return a ReactElement. ```tsx import Markdown from 'react-native-markdown-renderer'; import { Text, View } from 'react-native'; import type { ASTNode } from 'react-native-markdown-renderer'; function myRenderer(nodes: ASTNode[]) { return ( {nodes.map((node) => ( {node.content || node.type} ))} ); } const App = () => ( {'# Hello'} ); ``` -------------------------------- ### Default Styles Object Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/wiki/API-Reference.md The default styles object. See [Custom Styles](Custom-Styles) for all available keys. ```tsx const styles: MarkdownStyles; ``` -------------------------------- ### `blockPlugin` Function Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference An internal markdown-it plugin used for handling block-level token processing. ```APIDOC ## `blockPlugin` Function ### Description Internal markdown-it plugin for block-level token handling. ### Parameters - `md` (MarkdownIt) - The markdown-it instance to apply the plugin to. ``` -------------------------------- ### Custom AST Rendering with AstRenderer Source: https://context7.com/mientjan/react-native-markdown-renderer/llms.txt Use AstRenderer for custom rendering pipelines outside the Markdown component. Extend default rules or provide entirely new ones. Requires manual tokenization and AST generation. ```tsx import { AstRenderer, renderRules, styles as defaultStyles, stringToTokens, tokensToAST, MarkdownIt, } from 'react-native-markdown-renderer'; import type { ASTNode, RenderRules } from 'react-native-markdown-renderer'; // Extend default rules with a custom `unknown` fallback const extendedRules: RenderRules = { ...renderRules, unknown: (node: ASTNode, children, _parent, styles) => { console.warn(`Unhandled node type: ${node.type}`); return null; }, }; const renderer = new AstRenderer( extendedRules, { ...defaultStyles, text: { fontSize: 16, lineHeight: 26 } }, { onLinkPress: (url) => console.log('link:', url), allowedImageHandlers: ['https://'], defaultImageHandler: null, maxTopLevelChildren: 10, debugPrintTree: false, } ); // Manual pipeline usage: const md = new MarkdownIt({ typographer: true }); const source = '# Title\n\nParagraph with **bold**.'; const tokens = stringToTokens(source, md); const ast: ASTNode[] = tokensToAST(tokens as any); const element = renderer.render(ast); // element is a wrapping all rendered nodes ``` -------------------------------- ### PluginContainer Constructor Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/Plugins The `PluginContainer` class wraps a markdown-it plugin and its options. It is used to pass plugins to the `Markdown` component. ```typescript class PluginContainer { constructor(plugin: T, ...options: unknown[]); } ``` -------------------------------- ### AstRendererOptions Interface Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/wiki/API-Reference.md Configuration options for the AstRenderer, controlling aspects like link press handling, debugging, and image handling. ```APIDOC ## AstRendererOptions Interface ### Description Configuration options for the AstRenderer, controlling aspects like link press handling, debugging, and image handling. See [Custom Renderer](Custom-Renderer) for usage. ### Interface Definition ```typescript interface AstRendererOptions { onLinkPress?: (url: string) => boolean | void; debugPrintTree?: boolean; maxTopLevelChildren?: number | null; topLevelMaxExceededItem?: ReactNode; allowedImageHandlers?: string[]; defaultImageHandler?: string | null; } ``` ``` -------------------------------- ### Custom Link Handler with `onLinkPress` Source: https://context7.com/mientjan/react-native-markdown-renderer/llms.txt Intercept link taps to handle them internally or suppress the default browser behavior. Return `true` to prevent `Linking.openURL()`. ```tsx import React from 'react'; import { Alert } from 'react-native'; import Markdown from 'react-native-markdown-renderer'; export default function LinkHandlerExample() { const handleLinkPress = (url: string): boolean | void => { if (url.startsWith('mailto:')) { Alert.alert('Email', `Would send email to: ${url.replace('mailto:', '')}`); return true; // suppress default } if (url.includes('internal.app')) { // handle deep links internally console.log('Deep link:', url); return true; } // return nothing → falls through to Linking.openURL(url) }; return ( {'[Open Browser](https://example.com) [Send Email](mailto:hello@example.com) [App Screen](https://internal.app/screen)'} ); } ``` -------------------------------- ### Default Styles Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference The default styles object. Provides default styling for markdown elements. Refer to Custom Styles for all available keys. ```tsx const styles: MarkdownStyles; ``` -------------------------------- ### Importing Markdown Types with TypeScript Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/Migration-from-v3 Runtime prop validation is removed in v4. Use TypeScript for type checking by importing necessary types. ```tsx import type { MarkdownProps } from 'react-native-markdown-renderer'; ``` -------------------------------- ### `parser` Function Source: https://github.com/mientjan/react-native-markdown-renderer/blob/master/wiki/API-Reference.md A low-level parser function that tokenizes a markdown source string and passes the resulting Abstract Syntax Tree (AST) to a provided renderer. ```APIDOC ## `parser` Function ### Description Low-level parser function. Tokenizes the source string and passes the AST to the renderer. ### Signature ```tsx function parser( source: string, renderer: (nodes: ASTNode[]) => ReactElement, markdownIt: MarkdownIt ): ReactElement; ``` ``` -------------------------------- ### ASTNode Interface Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference Defines the structure of an Abstract Syntax Tree node used by the renderer. Includes properties like type, content, and children. ```tsx interface ASTNode { type: string; sourceType: string; sourceInfo: string; sourceMeta: unknown; block: boolean; markup: string; key: string; content: string; tokenIndex: number; index: number; attributes: Record; children: ASTNode[]; } ``` -------------------------------- ### Image URL Validation with `allowedImageHandlers` and `defaultImageHandler` Source: https://context7.com/mientjan/react-native-markdown-renderer/llms.txt Control which URI schemes are permitted for images. Disallowed schemes can be dropped entirely by setting `defaultImageHandler` to `null`. ```tsx import Markdown from 'react-native-markdown-renderer'; // Only allow HTTPS and base64 PNGs; drop everything else export default function SecureImageMarkdown() { return ( {` ![OK - HTTPS](https://example.com/photo.jpg) ![OK - base64](data:image/png;base64,iVBORw0KGgo=) ![SKIPPED - HTTP](http://example.com/insecure.jpg) ![SKIPPED - relative](./local-asset.png) `} ); } ``` -------------------------------- ### AstRenderer Class Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference Combines render rules and styles into a renderer. Use this class to create a custom renderer for markdown AST nodes. ```tsx class AstRenderer { constructor(renderRules: RenderRules, style?: MarkdownStyles); getRenderFunction(type: string): RenderFunction; renderNode(node: ASTNode, parentNodes: ASTNode[]): ReactNode; render(nodes: ASTNode[]): ReactElement; } ``` -------------------------------- ### Low-level Parser Function Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference Tokenizes the source string and passes the AST to the renderer. This is a low-level function for custom parsing scenarios. ```tsx function parser( source: string, renderer: (nodes: ASTNode[]) => ReactElement, markdownIt: MarkdownIt ): ReactElement; ``` -------------------------------- ### `stringToTokens` Function Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference Converts a markdown string into an array of markdown-it tokens. ```APIDOC ## `stringToTokens` Function ### Description Converts a markdown string to markdown-it tokens. ### Parameters - `source` (string) - The markdown string. - `markdownIt` (MarkdownIt) - A markdown-it instance. ### Returns - `Token[]` - An array of markdown-it tokens. ``` -------------------------------- ### Default Render Rules Source: https://github.com/mientjan/react-native-markdown-renderer/wiki/API-Reference The default render rules object, containing render functions for all supported node types. Useful as a base when creating a custom AstRenderer. ```tsx const renderRules: RenderRules; ``` -------------------------------- ### Customize Markdown Styles with Deep Merging Source: https://context7.com/mientjan/react-native-markdown-renderer/llms.txt Apply custom styles to Markdown elements by passing a `MarkdownStyles` object to the `style` prop. The `mergeStyle={true}` prop (default) deep-merges custom styles with the library's defaults. ```tsx import Markdown from 'react-native-markdown-renderer'; import type { MarkdownStyles } from 'react-native-markdown-renderer'; const customStyles: Partial = { // Only fontSize and color override — fontWeight '600' from default is kept heading1: { fontSize: 40, color: '#1a1a2e' }, heading2: { fontSize: 28, color: '#16213e' }, strong: { fontWeight: '900' }, paragraph:{ marginVertical: 10 }, link: { color: '#e94560', textDecorationLine: 'underline' }, blockquote: { borderLeftWidth: 4, borderLeftColor: '#e94560', paddingHorizontal: 12, backgroundColor: '#f5f5f5', }, codeBlock: { backgroundColor: '#282c34', padding: 16, borderRadius: 8, // monospaceFont inherited from default }, }; export default function StyledMarkdown() { return ( {'# Styled Heading\n\n**Bold** and [link](https://example.com)\n\n> A quote\n\n```\ncode block\n```'} ); } ```