Math Formatting with KaTeX in React-Markdown using rehype-katex

14 DEC 2022

REACT

This guide assumes that you already have a ReactMarkdown component set up. If not, you can follow the instructions on the repository. This guide is not an official tutorial.

React-Markdown is one the most popular libraries for rendering Markdown in React, and it would be useful to be able to render math as well. Luckily, the existence of two libraries, remark-math and rehype-katex, make this a very easy task.

Setting Up the Component

Firstly, install the remark-math and rehype-katex libraries by running the following command:

npm i -S remark-math rehype-katex

Once installed, import the libraries into the component which holds your ReactMarkdown component as follows:

import remarkMath from 'remark-math' import rehypeKatex from 'rehype-katex' import 'katex/dist/katex.min.css'

It is important to import the CSS file for the text styling, as this is not done by the library.

Finally, we can apply these libraries to the ReactMarkdown component!

Pass an array to both the remarkPlugins and rehypePlugins props of the component, containing remarkMath and rehypeKatex respectively, as follows:

<ReactMarkdown {/* Other Props Go Here */} remarkPlugins={[ remarkMath ]} rehypePlugins={[ rehypeKatex ]} > $l = r\theta$ </ReactMarkdown>

If done correctly, this should already be displaying math correctly.

Inline math can be represented by surrounding it in single dollar signs (i.e., $math$), and math on its own line (in a block) can be represented by surrounding it in double dollar signs, as follows:

$$ math $$

For math on its own line, both $$ must be placed on separate lines to each other and the math between, otherwise it will not render properly.