Skip to content

Support Latex? #853

@jaswinprakash

Description

@jaswinprakash

i have tried the latex example in my app, but the output seems only renders markdown correctly but the latex equation showing as plain text , is this latex feature support in this module? or am i doing anything wrong?

below is my code example

import React from "react";
import Markdown, { Renderer, MarkedTokenizer, MarkedLexer } from "react-native-marked";

class CustomTokenizer extends MarkedTokenizer {
  // Override
  codespan(src) {
    const match = src.match(/^\$+([^\$\n]+?)\$+/);
    if (match?.[1]) {
      const text = match[1].trim();
      const token = {
        type: 'custom',
        raw: match[0], // should be the exact regex pattern match
        identifier: "latex", // Unique identifier for the token
        tokens: MarkedLexer(text), // optional, can be used if the markdown contains children
        args: { // optional, can be used to send more information to the renderer
          text: text,
        }
      };
      return token;
    }

    return super.codespan(src);
  }
}

class CustomRenderer extends Renderer {
  // Custom Token implementation
  custom(identifier, _raw, _children, args) {
    const text = args?.text;
    if (identifier === "latex") {
      const styles = {
        padding: 16,
        minWidth: "100%",
        backgroundColor: "#f6f8fa"
      };
      return this.code(text.trim(), "latex", styles);
    }
    return null;
  }
}

const renderer = new CustomRenderer();
const tokenizer = new CustomTokenizer();

const markdown = `
# 🧠 Markdown with LaTeX

This example showcases **Markdown** combined with _LaTeX_ rendering.

## 📌 Features

- Headings (like this one)
- **Bold**, *Italic*, ~~Strikethrough~~
- [Link](https://reactnative.dev)
- Images: ![React Native](https://reactnative.dev/img/header_logo.svg)
- Blockquotes:
  > Markdown is awesome!
- Lists:
  - Inline math: $a^2 + b^2 = c^2$
  - Block math:
    $$
    \\int_0^\\infty e^{-x^2} dx = \\frac{\\sqrt{\\pi}}{2}
    $$
- Code:
  \`\`\`js
  const greet = () => console.log("Hello");
  \`\`\`

## 🎯 Inline & Block Math

Text before inline: $E = mc^2$ and after.

And now a block:

$$
\\nabla \\cdot \\vec{E} = \\frac{\\rho}{\\varepsilon_0}
$$

---

> Math + Markdown = ❤️

`;

const ExampleComponent = () => {
  return (
    <Markdown
      value={markdown}
      flatListProps={{
        initialNumToRender: 8,
      }}
      renderer={renderer}
      tokenizer={tokenizer}
    />
  );
};

export default ExampleComponent;

emulator output is shown below,

Image

project details,

"react-native": "0.76.5",
"react": "18.3.1",
"expo": "~52.0.18",
"react-native-marked": "^6.0.7",
"react-native-svg": "^15.10.1",

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions